6

这就是我在 Java 中解析格式良好的 XML 文档的方法:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();

// text contains the XML content
Document doc = builder.parse(new InputSource(new StringReader(text)));

文本示例如下:

<a>
  <b/>
</a>

如何解析 DocumentFragment?例如,这个:

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

注意:如果可能的话,我想使用org.w3c.dom而不是其他库/技术。

4

3 回答 3

6

我只是想到了一个愚蠢的解决方案。我可以将片段包装在一个虚拟元素中,如下所示:

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

然后再次以编程方式过滤掉该虚拟元素,如下所示:

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));
}

但这有点蹩脚,让我们看看是否有任何其他解决方案。

于 2011-08-11T13:12:43.453 回答
0

进一步扩展已经给出的答案:

public static DocumentFragment stringToFragment(Document document, String source) throws Exception
{
    source = "<dummy>" + source + "</dummy>";
    Node node = stringToDom(source).getDocumentElement();
    node = document.importNode(node, true);
    DocumentFragment fragment = document.createDocumentFragment();
    NodeList children = node.getChildNodes();
    while (children.getLength() > 0)
    {
        fragment.appendChild(children.item(0));
    }
    return fragment;
}
于 2014-03-28T18:01:37.200 回答
-2

我建议不要使用 DOM API。它又慢又丑。

请改用流式 StAX。它内置在 JDK 1.6+ 中。您一次可以获取一个元素,如果您缺少一个根元素,它不会阻塞。

http://en.wikipedia.org/wiki/StAX

http://download.oracle.com/javase/6/docs/api/javax/xml/stream/XMLStreamReader.html

于 2011-08-11T17:41:34.003 回答