Insert XML document to a specific node on another XML document (java)

醉酒当歌 提交于 2020-01-15 12:33:22

问题


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:


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));
  }
}


来源:https://stackoverflow.com/questions/15269263/insert-xml-document-to-a-specific-node-on-another-xml-document-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!