如何使用Stax创建解析XML的Dom对象

时间:2010-11-18 16:39:32

标签: java stax staxmate

使用Stax解析XML以便为XML树的某些部分创建org.w3c.dom.Document对象时遇到一些困难。

例:
<根>
<的子>
< child> child 1< / child>
< child> child 2< / child>
< child> child 3< / child>
< /儿童>
< /根>
=>我想为每个< 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();

  • 测试2抛出HIERARCHY_REQUEST_ERR异常:


    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)

你能帮我吗?

祝你好运, Guillaume LEFEBVRE

2 个答案:

答案 0 :(得分:2)

New Staxmate版本2.0.1(http://wiki.fasterxml.com/StaxMateDownload提供)解决了这个问题。

谢谢StaxMan!

答案 1 :(得分:0)

看看这个:http://jira.codehaus.org/browse/STAXMATE-39 ......: - )