Java将XML文档附加到现有文档
我有两个我创建的XML文档,我想将这两个文档组合在一个新的信封中。 所以我有
National Weather Service... 5/19/2009 5/19/2009
和
31 Partly Cloudy 78
我想要做的是在根节点内组合两个:组合文档
我已经尝试创建一个临时文档并用文档的根节点替换子项:
我希望用两个文件的根元素替换两个空格,但我得到“WRONG_DOCUMENT_ERR:一个节点用在与创建它的文档不同的文档中。” 我尝试采用和导入根节点,但我得到了同样的错误。
是否有一些简单的方法来组合文档而不必阅读并为每个节点创建新元素?
编辑:示例代码片段现在只是尝试将一个移动到“空白”文档… importNode和adoptNode函数不能导入/采用Document节点,但它们无法导入元素节点及其子树…或者如果它确实,它似乎不适用于追加/替换仍然。
Document xmlDoc; //created elsewhere Document weather = getWeather(latitude, longitude); Element weatherRoot = weather.getDocumentElement(); Node root = xmlDoc.getDocumentElement(); Node adopt = weather.adoptNode(weatherRoot); Node imported = weather.importNode(weatherRoot, true); Node child = root.getFirstChild(); root.replaceChild(adopt, child); //initially tried replacing the elements root.replaceChild(imported, child); root.appendChild(adopt); root.appendChild(imported); root.appendChild(adopt.cloneNode(true));
所有这些抛出DOMException:WRONG_DOCUMENT_ERR:节点用于与创建它的文档不同的文档中。
我想我将不得不弄清楚如何使用stax或只是重读文档并创建新元素……但是,这类似于组合文档似乎太多了。
这有点棘手,但以下示例运行:
public static void main(String[] args) { DocumentImpl doc1 = new DocumentImpl(); Element root1 = doc1.createElement("root1"); Element node1 = doc1.createElement("node1"); doc1.appendChild(root1); root1.appendChild(node1); DocumentImpl doc2 = new DocumentImpl(); Element root2 = doc2.createElement("root2"); Element node2 = doc2.createElement("node2"); doc2.appendChild(root2); root2.appendChild(node2); DocumentImpl doc3 = new DocumentImpl(); Element root3 = doc3.createElement("root3"); doc3.appendChild(root3); // root3.appendChild(root1); // Doesn't work -> DOMException root3.appendChild(doc3.importNode(root1, true)); // root3.appendChild(root2); // Doesn't work -> DOMException root3.appendChild(doc3.importNode(root2, true)); }
我知道你已经解决了这个问题,但是我仍然希望使用我正在测试的XOM库(与这个问题相关)来解决这个问题 ,并且在这样做时,提供一种不同于Andreas_D的回答。
(为简化此示例,我将
和
放入单独的文件中,我将其读入nu.xom.Document
实例。)
import nu.xom.*; [...] Builder builder = new Builder(); Document alertDoc = builder.build(new File("src/xomtest", "alertset.xml")); Document weatherDoc = builder.build(new File("src/xomtest", "weatherset.xml")); Document mainDoc = builder.build(" ", ""); Element root = mainDoc.getRootElement(); root.replaceChild( root.getFirstChildElement("blank"), alertDoc.getRootElement().copy()); root.replaceChild( root.getFirstChildElement("blank"), weatherDoc.getRootElement().copy());
关键是要复制要插入mainDoc
的元素; 否则你会抱怨“孩子已经有了父母”。
现在输出mainDoc给出:
National Weather Service... 5/19/2009 5/19/2009 31 Partly Cloudy 78
令我高兴的是,事实certificate这与XOM非常直截了当。 写这篇文章只花了几分钟,尽管我对图书馆还不是很有经验。 (没有
元素会更容易,即从
。)
因此,除非您有充分理由仅使用标准JDK工具,否则我强烈建议您尝试使用XOM,因为它可以使Java中的XML处理更加愉快。