简体   繁体   中英

Append a xml node to a existing xml file from a another xml file using java

I'm having two xml files as shown below and I need to read a node from one xml and append that node to another xml file.

Xml file :1

<A>
  <B>
    <c>1<c/>
    <d>2<d/>
    <e>3<e/>
  </B>
</A>

Xml file :2

<AA>
  <BB>
    <cc>1<cc/>
    <dd>2<dd/>
    <ee>3<ee/>
    <ff>
       <gg>4</gg>
    <ff>
  </BB>
</AA>

RESULT

<A>
    <B>
      <BB>
        <cc>1<cc/>
        <dd>2<dd/>
        <ee>3<ee/>
        <ff>
           <gg>4</gg>
        <ff>
      </BB>
        <c>1<c/>
        <d>2<d/>
        <e>3<e/>
    </B>
</A>

Any advice you could give is much appreciated.

To expand on Lucas's first comment above you could try using SimpleXML to read the two XML files into memory aka 'deserialization'. Example code for reading XML into in memory objects looks like this:

Serializer serializer = new Persister();
File source = new File("example.xml");

Example example = serializer.read(Example.class, source);

Then, once you have combined the two results into a third object you can also use SimpleXML to write the third object to a file aka 'serialization'.

Example code for writing an XML file using in memory data:

Serializer serializer = new Persister();
Example example = new Example("Example message", 123);
File result = new File("example.xml");

serializer.write(example, result);

SimpleXML has a good tutorial and can be imported by adding a Maven dependency .

Spend a little time reading the tutorial and it should get you going in the right direction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM