我创建了两个 XML 文档,我想将这两个文档合并到一个新信封中。所以我有
<alert-set>
<warning>National Weather Service...</warning>
<start-date>5/19/2009</start-date>
<end-date>5/19/2009</end-date>
</alert-set>
和
<weather-set>
<chance-of-rain type="percent">31</chance-of-rain>
<conditions>Partly Cloudy</conditions>
<temperature type="Fahrenheit">78</temperature>
</weather-set>
我想做的是将两者结合在一个根节点内:
我已经尝试创建一个临时文档并用文档的根节点替换子节点:
<DataSet>
<blank/>
<blank/>
</DataSet>
我希望用两个文档的根元素替换这两个空白,但我得到“WRONG_DOCUMENT_ERR:一个节点在与创建它的文档不同的文档中使用。”我尝试采用并导入根节点,但出现相同的错误。
有没有一些简单的方法可以合并文档,而不必通读每个节点并为每个节点创建新元素?
编辑:示例代码片段 现在只是尝试将一个移动到“空白”文档中...... importNode 和 adoptNode 函数无法导入/采用文档节点,但它们无法导入元素节点及其子树......或者如果可以,它可以似乎仍然无法用于 append/替换。
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 <blank/> 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));
}
关于Java 将 XML 文档 append 到现有文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/883987/