How to create Dom objects parsing an XML with Stax

一笑奈何 提交于 2019-12-25 03:54:05

问题


I have some difficulties to parse an XML using Stax in order to create org.w3c.dom.Document objects for parts of the XML tree.

Ex.:
<root>
<children>
<child>child 1</child>
<child>child 2</child>
<child>child 3</child>
</children>
</root>
=> I would like to create 3 DOM objects for each <child> node.

I tried to do this using Staxmate and DomConverter but I have a problem ...

My test project only depends on :

  • stax2-api-3.0.3.jar
  • staxmate-2.0.0.jar
  • jdk 1.6.0_21

2 tests :

  • Test 1 that works perfectly


    FileInputStream in = new FileInputStream("demo.xml");
    XMLStreamReader sr = XMLInputFactory.newInstance().createXMLStreamReader(in);
    Document doc = new DOMConverter().buildDocument(sr);
    in.close();
  • Test 2 that throws a HIERARCHY_REQUEST_ERR exception :


    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)

Could you help me please ?

Best regards, Guillaume LEFEBVRE


回答1:


New Staxmate release 2.0.1 (available at http://wiki.fasterxml.com/StaxMateDownload) solved this issue.

Thank you StaxMan !




回答2:


Check out this: http://jira.codehaus.org/browse/STAXMATE-39... :-)



来源:https://stackoverflow.com/questions/4217275/how-to-create-dom-objects-parsing-an-xml-with-stax

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!