[英]XML: to append xml document into the node of another document
我必須將file1.xml元素插入另一個file2.xml。 file2.xml有幾個節點,每個節點都有node_id。 有沒有辦法做到這一點。
讓我們假設:
file1.xml:
< root>
<node_1>......</node_1>
</root>
file2.xml:
< root>
< node>
< node_id>1'<'/node_id>
< /node>
< /root>
我想要 ? file2.xml:
< root>
< node>
<node_1>......</node_1> [here i want to append the file1.xml]
</node>
</root>
以下代碼說明了這一點:
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
//build DOMs
Document doc1 = builder.parse(new File("file1.xml"));
Document doc2 = builder.parse(new File("file2.xml"));
//get all node_ids from doc2 and iterate
NodeList list = doc2.getElementsByTagName("node_id");
for(int i = 0 ; i< list.getLength() ; i++){
Node n = list.item(i);
//extract the id
String id = n.getTextContent();
//now get all node_id elements from doc1
NodeList list2 = doc1.getElementsByTagName("node_"+id);
for(int j = 0 ; j< list2.getLength() ; j++){
Node m = list2.item(j);
//import them into doc2
Node imp = doc2.importNode(m,true);
n.getParent().appendChild(imp);
}
}
//write out the modified document to a new file
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
Source source = new DOMSource(doc2);
Result output = new StreamResult(new File("merged.xml"));
transformer.transform(source, output);
結果將是:
<root>
<node>
<node_id>1</node_id>
<node_1>This is 1</node_1>
</node>
<node>
<node_id>2</node_id>
<node_2>This is 2</node_2>
</node>
<node>
<node_id>3</node_id>
<node_3>This is 3</node_3>
</node>
</root>
通常的做法:
將file1和file2中的Document
解析為Document
對象(SAXParser,jDom,dom4j),然后將元素<node_1>
從第一個文檔導入到第二個文檔,並將其添加到<node>
。 然后刪除相應的<node_id>
元素。
導入是必要的, Document
實現為此過程提供了正確的方法! 只需將一個文檔中的元素添加到另一個文檔中,就會產生DOMExceptions
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.