How to parse a documentfragment using the Java standard DOM API

This is how I parse well formed XML documents 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 of a text is:

<a>
  <b/>
</a>

How do I parse a documentfragment? For example, this:

<a>
  <b/>
</a>
<a>
  <b/>
</a>

Note: if possible, I would like to use org w3c. DOM without using other libraries / technologies

Solution

I just came up with a stupid solution I can wrap fragments in such virtual elements:

<dummy><a>
  <b/>
</a>
<a>
  <b/>
</a></dummy>

The virtual element is then programmatically filtered out again as follows:

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 it's a bit lame. Let's see if there are other solutions

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>