String as a document

I follow this turorial when parsing XML using XPath, and it gives the following example to open a document:

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true); // never forget this!
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("books.xml");

What I would like to do is change, so it Documentreads a variable Stringthat I have already done, instead of reading from a file. How can i do this?

+3
source share
3 answers
builder.parse(new InputSource(new StringReader("<some><xml></xml></some>")));
+5
source

Look here

DocumentBuilderFactory dbf =
        DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xmlRecords));

    Document doc = db.parse(is);
+2
source

You can try the following:

public static Document stringToDom(String xmlSource) 
        throws SAXException, ParserConfigurationException, IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    return builder.parse(new InputSource(new StringReader(xmlSource)));
}
0
source

Source: https://habr.com/ru/post/1776989/


All Articles