-1

I am new to XML parsing in Java I have an XML file

<root>
    <project name="A">
        <Sub name="abc">
            <first property1="ab" property2="cd" property3="ed"/>
            <second property1="aa" property2="dd" property3="ke"/>
        </Sub>
    </project>
</root>

I need to add another node as second with different property values (i.e.,)

<root>
    <project name="A">
        <Sub name="abc">
            <first property1="ab" property2="cd" property3="ed"/>
            <second property1="aa" property2="dd" property3="ke"/>
            <second property1="oa" property2="ld" property3="je"/>
        </Sub>
    </project>
</root>

Can anyone tell me how to go ahead and implement in java?

Aadi Droid
  • 1,689
  • 4
  • 22
  • 46
user3131471
  • 71
  • 1
  • 6

2 Answers2

2

You can do it using jdom. Include jdom jar in your classpath.

            Document document = (Document) new SAXBuilder().build(new File("E:/input.xml"));
            Element sub = document.getRootElement().getChild("project").getChild("Sub");            
            Element second = new Element("second");
            second.setAttribute("property1", "aa");
            second.setAttribute("property2", "dd");

            sub.addContent(second);

            XMLOutputter xmlOutput = new XMLOutputter();
            xmlOutput.setFormat(Format.getPrettyFormat().setOmitDeclaration(true));         
            xmlOutput.output(document, System.out);
Sinto
  • 920
  • 5
  • 10
0

I would follow this sequence :

  1. Deserialize this data into a java object XML to Java Object
  2. Edit it by adding whatever and dump the xml into the file
Community
  • 1
  • 1
Aadi Droid
  • 1,689
  • 4
  • 22
  • 46