我在使用 Stax 解析 XML 以便为部分 XML 树创建 org.w3c.dom.Document 对象时遇到一些困难。
例如:
<root>
<children>
<child>child 1</child>
<child>child 2</child>
<child>child 3</child>
</children>
</root>
=> 我想为每个 <child> 节点创建 3 个 DOM 对象。
我尝试使用 Staxmate 和 DomConverter 来做到这一点,但我遇到了问题......
我的测试项目仅取决于:
- stax2-api-3.0.3.jar
- staxmate-2.0.0.jar
- JDK 1.6.0_21
2个测试:
- 完美运行的测试 1
FileInputStream in = new FileInputStream("demo.xml");
XMLStreamReader sr = XMLInputFactory.newInstance().createXMLStreamReader(in);
Document doc = new DOMConverter().buildDocument(sr);
in.close();
- 引发 HIERARCHY_REQUEST_ERR 异常的测试 2:
FileInputStream in = new FileInputStream("demo.xml");
XMLStreamReader sr = XMLInputFactory.newInstance().createXMLStreamReader(in);
while (sr.hasNext()) {
sr.next();
switch (sr.getEventType()) {
case XMLStreamReader.START_ELEMENT:
Document doc = new DOMConverter().buildDocument(sr);
}
}
in.close();
org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted.
at com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl.insertBefore(CoreDocumentImpl.java:391)
at com.sun.org.apache.xerces.internal.dom.NodeImpl.appendChild(NodeImpl.java:235)
at org.codehaus.staxmate.dom.DOMConverter._build(DOMConverter.java:292)
at org.codehaus.staxmate.dom.DOMConverter.buildDocument(DOMConverter.java:171)
at org.codehaus.staxmate.dom.DOMConverter.buildDocument(DOMConverter.java:152)
at org.codehaus.staxmate.dom.DOMConverter.buildDocument(DOMConverter.java:131)
at com.staxmatetest.Main.main(Main.java:22)
请问你能帮帮我吗 ?
最好的问候, 纪尧姆 LEFEBVRE