tags:

views:

50

answers:

2

I want to append an attribute an existing element in XML using Java. For example:

<employee>
<details name="Jai" age="25"/>
<details name="kishore" age="30"/>
</employee>

It want to add weight to it (assume that it is calculated and then appended in response). How can I append that to all items?

<details name="Jai" age="25" weight="55"/>
A: 
import org.w3c.dom.*;
import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

public class AddAndPrint {

  public static void main(String[] args) {    
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.parse("/path/to/file.xml");
    NodeList employees = document.getElementsByTagName("employee");
    for (Node employee : employees) {
      for (Node child : employee.getChildNodes() {
        if ("details".equals(child.getNodeName()) child.setAttribute("weight", "150");
       }
     }

     try {
       Source source = new DOMSource(doc);
       StringWriter stringWriter = new StringWriter();
       Result result = new StreamResult(stringWriter);
       TransformerFactory factory = TransformerFactory.newInstance();
       Transformer transformer = factory.newTransformer();
       transformer.transform(source, result);
       System.out.println(stringWriter.getBuffer().toString());
     } catch (TransformerConfigurationException e) {
       e.printStackTrace();
     } catch (TransformerException e) {
       e.printStackTrace();
     }
  }
}
Eric Hauser
Thanks Eric it worked..
Jeba
Could you mark my answer as accepted then?
Eric Hauser
A: 

Here is a quick solution based on jdom:

public static void main(String[] args) throws JDOMException, IOException {
    File xmlFile = new File("employee.xml");
    SAXBuilder builder = new SAXBuilder();
    Document build = builder.build(xmlFile);        
    XPath details = XPath.newInstance("//details");
    List<Element> detailsNodes = details.selectNodes(build);
    for (Element detailsNode:detailsNodes) {
        detailsNode.setAttribute("weight", "70");  // static weight for demonstration
    }
    XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
    outputter.output(build, System.out);
}

First, we build a document (SAXBuilder), next we create a XPath expression for the details node, then we iterate through the elements for that expression and add the weight attribute.

The last two lines just verify that it's white magic :-)

Andreas_D
Thanks Andreas_D though i'm using DOM for XML Parsing..
Jeba