Add new attributes to an existing XML node in java?

user2966458 picture user2966458 · Nov 18, 2013 · Viewed 43.8k times · Source

I want to add an attribute to an existing xml node.I don't want to add new elements (new nodes) to my xml file, I just want to add a new attribute. How can I do this?

In particular I've tried this lines of code:

Element process = doc.getElementsById("id");
    process.setAttribute("modelgroup", "");

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new  File("C:\\Users\\Blerta\\workspaceKEPLER\\XML_to_JSON\\SampleExample.xml"));
transformer.transform(source, result);

But I get the following exception:

Exception in thread "main" java.lang.NullPointerException
    at Main.appendAttributes(Main.java:172)
    at Main.displayNodes(Main.java:65)
    at Main.displayNodes(Main.java:138)
    at Main.main(Main.java:42)**

Answer

subash picture subash · Nov 18, 2013

in DOM parser it is very easy. get your node and simply use this function.

((Element)node).setAttribute("attr_name","attr_value");

then finally update your document. like this..

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "5");
        DOMSource source = new DOMSource(document);
        StreamResult result = new StreamResult(new File(tablePath));
        transformer.transform(source, result);