繁体   English   中英

在DOM文档Java的DOM中间附加一个Element Child

[英]Append an Element Child on a DOM middle of a DOM document Java

我有两个相同的文档,我想将文档中的一个或多个元素附加到anotehr。 但是,当我这样做时,出现诸如“空异常”之类的错误

XML的语法与以下示例相同:

<var1 code="1">
<elementVar1 attribute1="0" attribute2="67" attribute3="SP-5046"/>
<elementVar1 attribute1="0" attribute2="63" attribute3="SP-5042"/>
<elementVar1 attribute1="0" attribute2="62" attribute3="SP-5041"/>
<elementVar1 attribute1="0" attribute2="61" attribute3="SP-5040"/>
<elementVar1 attribute1="0" attribute2="48" attribute3="SP-5027"/>
<elementVar1 attribute1="0" attribute2="47" attribute3="SP-5026"/>
<elementVar1 attribute1="0" attribute2="46" attribute3="SP-5025"/>
</var1>
<var1 code="1">
<elementVar1 attribute1="0" attribute2="67" attribute3="SP-5046"/>
<elementVar1 attribute1="0" attribute2="63" attribute3="SP-5042"/>
<elementVar1 attribute1="0" attribute2="46" attribute3="SP-5025"/>
</var1>

Java代码是这样写的:

// docCurrent and docNew is already filled with the same syntax
NodeList nlC = docCurrent.getElementsByTagName("elementVar1");
NodeList nlN = docNew.getElementsByTagName("elementVar1");
Element elementNew = (Element)nlN.item(3);
Element element = (Element)nlC.item(1);
element.getParentNode().appendChild(elementNew); // The error Null Exception occurrs here

是否有任何其他方法可以从文档中获取元素并将其附加到另一个文档中?

好的,我设法将一个元素子元素附加到另一个DOM树。

NodeList nlC = docCurrent.getElementsByTagName("elementVar1");
NodeList nlN = docNew.getElementsByTagName("elementVar1");
Element elementNew = (Element)nlN.item(3);
Node copiedNode = docNew.importNode(elementNew, true);
docCurrent.getDocumentElement().appendChild(copiedNode);

这对我有用。

问候,

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM