Insert XML document to a specific node on another

2019-08-07 09:21发布

I have an XML1:

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

... and XML 2:

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

I want to insert XML 2 in XML 1 document on the expandedData node using JAVA.

The final XML1 should look like:

<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 inserted on the XML1's expandedData node. Any ideas? I know i need to build a recursive function to loop through XML 2 but not sure how to implement it in java.

1条回答
beautiful°
2楼-- · 2019-08-07 09:44

Consider using 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));
  }
}
查看更多
登录 后发表回答