将XML文档插入另一个XML文档(java)上的特定节点

时间:2013-03-07 10:54:00

标签: java xml xmldocument appendchild

我有一个XML1:

<letterContent>
    <key1>key1</key1>
    <key2>key2</key2>
    <type>456</type>
    <object1>789</object1>
    <effectiveDate>00</effectiveDate>
    <expandedData />
</letterContent>

...和XML 2:

<expandedData>
    <rsnForReg>
        <legacyTIN>
            <asCurrent>leg123</asCurrent>
        </legacyTIN>
        <etpmTIN>
            <asCurrent>etpm123</asCurrent>
        </etpmTIN>
        <regType>
            <asCurrent/>
        </regType>
    </rsnForReg>
</expandedData>

我想使用JAVA在extendedData节点上的XML 1文档中插入XML 2。

最终的XML1应如下所示:

<letterContent>
    <key1>key1</key1>
    <key2>key2</key2>
    <type>456</type>
    <object1>789</object1>
    <effectiveDate>00</effectiveDate>
    <expandedData>
        <rsnForReg>
            <legacyTIN>
                <asCurrent>leg123</asCurrent>
            </legacyTIN>
            <etpmTIN>
                <asCurrent>etpm123</asCurrent>
            </etpmTIN>
            <regType>
                <asCurrent/>
            </regType>
        </rsnForReg>
    </expandedData>
</letterContent>

XML2插入XML1的expandedData节点。有任何想法吗?我知道我需要构建一个递归函数来循环遍历XML 2但不确定如何在java中实现它。

1 个答案:

答案 0 :(得分:1)

考虑使用XPath

import static javax.xml.xpath.XPathConstants.*;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.*;
import org.w3c.dom.*;
import org.xml.sax.InputSource;

public class Xml2into1 {
  public static void main(String[] args) throws Exception {
    // read from files
    InputSource xml1 = new InputSource("xml1.xml");
    InputSource xml2 = new InputSource("xml2.xml");
    // find the node to add to
    XPath xpath = XPathFactory.newInstance()
        .newXPath();
    Node expandedData1 = (Node) xpath.evaluate("//expandedData", xml1, NODE);
    Document doc1 = expandedData1.getOwnerDocument();
    // insert the nodes
    Node expandedData2 = (Node) xpath.evaluate("//expandedData", xml2, NODE);
    expandedData1.getParentNode()
        .replaceChild(doc1.adoptNode(expandedData2), expandedData1);
    // print results
    TransformerFactory.newInstance()
        .newTransformer()
        .transform(new DOMSource(doc1), new StreamResult(System.out));
  }
}