274

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?

bluish
  • 26,356
  • 27
  • 122
  • 180
Dewayne
  • 3,682
  • 3
  • 25
  • 23

6 Answers6

517

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

Community
  • 1
  • 1
shsteimer
  • 28,436
  • 30
  • 79
  • 95
20

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. 
Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
Uri
  • 88,451
  • 51
  • 221
  • 321
8

Convert the string to an InputStream and pass it to DocumentBuilder

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

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

Christophe Roussy
  • 16,299
  • 4
  • 85
  • 85
Akbar ibrahim
  • 5,110
  • 3
  • 26
  • 23
  • 1
    I'd prefer the StringReader because it avoids String.getBytes(), but this should *usually* work also. – Michael Myers Feb 18 '09 at 18:19
  • 3
    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 Feb 18 '09 at 18:38
6

I'm using this method

public Document parseXmlFromString(String xmlString){
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputStream inputStream = new    ByteArrayInputStream(xmlString.getBytes());
    org.w3c.dom.Document document = builder.parse(inputStream);
    return document;
}
Yasir Shabbir Choudhary
  • 2,458
  • 2
  • 27
  • 31
5

javadocs show that the parse method is overloaded.

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

duffymo
  • 305,152
  • 44
  • 369
  • 561
0

You can use the Scilca XML Progession package available at GitHub.

XMLIterator xi = new VirtualXML.XMLIterator("<xml />");
XMLReader xr = new XMLReader(xi);
Document d = xr.parseDocument();
Shukant Pal
  • 706
  • 6
  • 19