0

I have the following 2 xmls:

Xml1:

<Sctn>
  <CI>
  <G>WCARD_HM</G>
  <Ty>INFO</Ty>
  <Tt>3600</Tt>
  <Ts>1395118210.1</Ts>
  </CI>
</Sctn>

XML2:

<CI>
  <G>WCARD_Off</G>
  <Ty>Test</Ty>
  <Tt>1234</Tt>
  <Ts>1395derr</Ts>
</CI>

Now, I want to add xml2 to Sctn tag of Xml1. ie, the resulting xml should be:

<Sctn>
      <CI>
        <G>WCARD_HM</G>
        <Ty>INFO</Ty>
        <Tt>3600</Tt>
        <Ts>1395118210.1</Ts>
      </CI>
      <CI>
        <G>WCARD_Off</G>
        <Ty>Test</Ty>
        <Tt>1234</Tt>
        <Ts>1395derr</Ts>
      </CI>
</Sctn>

Is there a way to do this without iterating over every element of Xml2 ?

Saurabh Verma
  • 6,328
  • 12
  • 52
  • 84
  • If simple string manipulation is an option it's easily done via lastIndexOf("") and substring() then just concatenate the different parts. – Vinc Mar 18 '14 at 07:25
  • http://stackoverflow.com/questions/648471/merge-two-xml-files-in-java There were lot of posts similar to yours. http://stackoverflow.com/questions/5681597/how-to-merge-two-xmls-in-java and http://stackoverflow.com/questions/80609/merge-xml-documents and many others. – RMachnik Mar 18 '14 at 07:25
  • I would prefer not to change Element object to String and then back to Element – Saurabh Verma Mar 18 '14 at 07:26
  • True, xmls always been a pain to work with in java,for me atleast. Personally only ever read xml with java, never manipulated. – Vinc Mar 18 '14 at 07:33

1 Answers1

0

Quite simple, actually (even with DOM standards):

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();

    Document d1 = builder.parse(...);
    Document d2 = builder.parse(...);

    d1.getDocumentElement().appendChild(d1.importNode(d2.getDocumentElement(), true));
forty-two
  • 12,204
  • 2
  • 26
  • 36