Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to append node from xml document to existing xml document

Tags:

java

dom

xml

I have list of tournaments in my a.xml:

<tournaments>

    <tournament>
        <name>a</name>
    </tournament>

    <tournament>
        <name>b</name>
    </tournament>

    <tournament>
        <name>c</name>
    </tournament>

</tournaments>

ad then I have one tournament in b.xml

<tournament>
    <name>d</name>
</tournament>

How I can apend document b.xml to a.xml into as another tournament ?

so this is what I want:

<tournaments>

    <tournament>
        <name>a</name>
    </tournament>

    <tournament>
        <name>b</name>
    </tournament>

    <tournament>
        <name>c</name>
    </tournament>

    <tournament>
        <name>d</name>
    </tournament>

</tournaments>
like image 449
hudi Avatar asked Nov 01 '11 09:11

hudi


1 Answers

  1. Get Node to add from first Document;
  2. Adopt Node (see Document.adopt(Node)) from first Document to the second Document;
  3. Appent adopted Node as a child to second Document structure (see Node.appendChild(Node).

Update. Code:

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();

Document tournament = builder.parse(new File("b.xml"));
Document tournaments = builder.parse(new File("a.xml"));

Node tournamentElement = tournament.getFirstChild();
Node ndetournament = tournaments.getDocumentElement();
Node firstDocImportedNode = tournaments.adoptNode(tournamentElement);
ndetournament.appendChild(firstDocImportedNode);

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(new DOMSource(tournaments), new StreamResult(System.out));

Result:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<tournaments>
    <tournament>
        <name>a</name>
    </tournament>

    <tournament>
        <name>b</name>
    </tournament>

    <tournament>
        <name>c</name>
    </tournament>
<tournament>
    <name>d</name>
</tournament>
</tournaments>
like image 74
svaor Avatar answered Oct 16 '22 09:10

svaor