Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a DocumentFragment with with the Java standard DOM API

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.

like image 455
Lukas Eder Avatar asked Aug 11 '11 13:08

Lukas Eder


1 Answers

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.

like image 127
Lukas Eder Avatar answered Oct 26 '22 12:10

Lukas Eder