将子元素添加到元素 java (DOM)

Adding sub-element to element java (DOM)

本质上,我是从一个文件(数据库)创建一个 XML 文档,然后我将另一个已解析的 XML 文件(包含更新的信息)与原始数据库进行比较,然后将新信息写入数据库。

我正在使用 java 的组织。w3c.dom。

经过多次努力,我决定只创建一个新的 Document 对象,然后从我正在比较其中元素的 oldDocument 和 newDocument 对象中写入。

XML 文档采用以下格式:

<Log>
   <File name="something.c">
      <Warning file="something.c" line="101" column="23"/>
      <Warning file="something.c" line="505" column="71" />
   </File>
</Log>

举个例子。

我如何在不遇到讨厌的 "org.w3c.dom.DOMException: WRONG_DOCUMENT_ERR: A node is used in a different document than the one that created it." 异常的情况下向 "File" 添加新的 "warning" 元素?

把它砍下来,我有类似的东西:

public static Document update(Element databaseRoot, Element newRoot){
    Document doc = db.newDocument(); // DocumentBuilder defined previously

    Element baseRoot = doc.createElement("Log");

    //for each file i have:
    Element newFileRoot = doc.createElement("File");

    //some for loop that parses through each 'file' and looks at the warnings

    //when i come to a new warning to add to the Document:
    NodeList newWarnings = newFileToCompare.getChildNodes(); //newFileToCompare comes from the newRoot element

    for (int m = 0; m < newWarnings.getLength(); m++){

       if(newWarnings.item(m).getNodeType() == Node.ELEMENT_NODE){
          Element newWarning = (Element)newWarnings.item(m);

          Element newWarningRoot = (Element)newWarning.cloneNode(false);
          newFileRoot.appendChild(doc.importNode(newWarningRoot,true)); // this is what crashes
       }
    }

    // for new files i have this which works:
    newFileRoot = (Element)newFiles.item(i).cloneNode(true);
    baseRoot.appendChild(doc.importNode(newFileRoot,true));

    doc.appendChild(baseRoot);
    return doc;
}

有什么想法吗?我正在用头撞墙。第一次这样做。

通过调试器,我验证了文档所有者是正确的。使用node.getOwnerDocument(),我意识到newFileRoot在我之前创建它时连接到错误的文件,所以我改变了

Element newFileRoot = (Element)pastFileToFind.cloneNode(false);

Element newFileRoot = (Element)doc.importNode(pastFileToFind.cloneNode(false),true);

后来当我尝试将 newWarningRoot 添加到 newFileRoot 时,它们有不同的文档(newWarningRoot 是正确的,但 newFileRoot 连接到错误的文档)