This is how I can parse a well-formed XML document in Java:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
// text contains the XML content
Document doc = builder.parse(new InputSource(new StringReader(text)));
An example for text is this:
<a>
<b/>
</a>
How can I parse a DocumentFragment? For example, this:
<a>
<b/>
</a>
<a>
<b/>
</a>
NOTE: I want to use org.w3c.dom
and no other libraries/technologies, if possible.
I just thought of a silly solution. I could wrap the fragment in a dummy element like this:
<dummy><a>
<b/>
</a>
<a>
<b/>
</a></dummy>
And then programmatically filter out that dummy element again, like this:
String wrapped = "<dummy>" + text + "</dummy>";
Document parsed = builder.parse(new InputSource(new StringReader(wrapped)));
DocumentFragment fragment = parsed.createDocumentFragment();
// Here, the document element is the <dummy/> element.
NodeList children = parsed.getDocumentElement().getChildNodes();
// Move dummy's children over to the document fragment
while (children.getLength() > 0) {
fragment.appendChild(children.item(0));
}
But that's a bit lame, let's see if there is any other solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With