18

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)**
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
user2966458
  • 181
  • 1
  • 1
  • 5

4 Answers4

29

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);
payam_sbr
  • 1,428
  • 1
  • 15
  • 24
subash
  • 3,116
  • 3
  • 18
  • 22
  • 4
    I've allready tried this but I cannot apply setAttribute to the node – user2966458 Nov 18 '13 at 16:40
  • 2
    **doc.getElementsByTagName("process");** it is return NodeList. try like this. **NodeList list = doc.getElementsByTagName("process");**. Element el = (Element)list.item(0); then you can use el.setAttribute("attr_name","attr_val"); – subash Nov 18 '13 at 16:49
  • What if node isn't castable to Element? – Stephan Jun 29 '17 at 15:16
8

The easiest and the shortest is to cast the node to org.w3c.dom.Element and then invoke setAttribute on it:

((Element)aNode).setAttribute("name", "value");
Sergey Tarasov
  • 858
  • 11
  • 18
3

You could do it in a few lines using xslt. Oracle have a half decent tutorial with all the code snippets http://docs.oracle.com/javase/tutorial/jaxp/xslt/transformingXML.html

The key bit for your xslt would be something like the following:

    <xsl:template match="elementToAddNewAttrTo">
        <xsl:attribute name="newAttrName">NewAttrValue</xsl:attribute>
    </xsl:template>
stripybadger
  • 4,539
  • 3
  • 19
  • 26
1

Recommended approach:

Node node = ...;
if(node.getNodeType() == Node.ELEMENT_NODE)
{
    ((Element) node).setAttribute("name", "value");
}

Situational approach:

try
{
    // ...
    Node node = ...;
    ((Element) node).setAttribute("name", "value");
    // ...
}
catch(ClassCastException e)
{
    // Handle exception
}

Only use the try-catch approach if you already know that all the nodes that you process should be of type 'Element' (and thus any other case is an "exception" and should break from the code).

Yeti
  • 2,647
  • 2
  • 33
  • 37