Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (10.2k points)

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?

1 Answer

0 votes
by (46k points)

I have this purpose in my code base, this should serve 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);

}

Related questions

0 votes
1 answer
0 votes
1 answer
asked Jul 18, 2019 in Java by Shubham (3.9k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Nov 4, 2019 in Java by Anvi (10.2k points)
...