views:

1813

answers:

4

I have the following code: DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);

How can I get it to parse XML contained within a String instead of a file?

+3  A: 

javadocs show that the parse method is overloaded.

Create a StringStream or InputSource using your string XML and you should be set.

duffymo
+2  A: 

One way is to use the version of parse that takes an InputSource rather than a file

A SAX InputSource can be constructed from a Reader object. One Reader object is the StringReader

So something like

parse(new InputSource(new StringReader(myString))) may work.

Uri
+3  A: 

Convert the string to an InputStream and pass it to DocumentBuilder

ByteArrayInputStream stream = new ByteArrayInputStream(string.getBytes());
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
builder.parse(stream);

EDIT
In response to bendin's comment regarding encoding, see shsteimer's answer to this question.

Akbar ibrahim
I'd prefer the StringReader because it avoids String.getBytes(), but this should *usually* work also.
Michael Myers
When you call getBytes(), what encoding are you expecting it to use? How are you telling to the XML parser which encoding it's getting? Do you expect it to guess? What happens when you are on a platform where the default encoding isn't UTF-8?
bendin
+10  A: 

I have this function in my code base, this should work for you.

    public static Document loadXMLFromString(String xml) throws Exception
    {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(xml));
        return builder.parse(is);
    }

also see this similar question

shsteimer