如何将XmlCursor内容插入DOM Document

Jur*_*raj 2 java xml xmlbeans

有些API会返回指向XML Document根目录的XmlCursor.我需要将所有这些插入到另一个org.w3c.DOM表示的文档中.

在开始:XmlCursor poiting

<a> <b> some text </b> </a>

<foo>

</foo>

DOM文档:

<foo>

  <someOtherInsertedElement>

    <a> <b> some text </b> </a>

  </someOtherInsertedElement>

</foo>

document.importNode(cursor.getDomNode())

最后我希望将原始DOM文档更改为:

<a> <b> some text </b> </a>

<foo>

</foo>

注意:

<foo>

  <someOtherInsertedElement>

    <a> <b> some text </b> </a>

  </someOtherInsertedElement>

</foo> 不起作用 - 抛出异常:NOT_SUPPORTED_ERR:实现不支持所请求的对象或操作类型.

Sie*_*tse 6

尝试这样的事情:

Node originalNode = cursor.getDomNode();
Node importNode = document.importNode(originalNode.getFirstChild());
Node otherNode = document.createElement("someOtherInsertedElement");
otherNode.appendChild(importNode);
document.appendChild(otherNode);
Run Code Online (Sandbox Code Playgroud)

换句话说:

  1. 从光标获取DOM节点.在这种情况下,它是一个DOMDocument,getFirstChild()也可以获取根节点.
  2. 将其导入DOMDocument.
  3. 使用DOMDocument做其他事情.
  4. 将导入的节点附加到正确的节点.

导入的原因是节点始终"属于"给定的DOMDocument.只添加原始节点会导致异常.