1

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"/>
1
  • 2
    Are you already using a library to parse this xml and turn it into object or a data structure? Any answer to your question is going to be dependent upon what you are already using. Commented Jul 5, 2010 at 18:45

2 Answers 2

3
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();
     }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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 :-)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.