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)**
Add a new attribute to the element, using setAttribute(String name, String value) . Call void prettyPrint(Document xml) method of the example. The method gets the xml Document and converts it into a formatted xml String, after transforming it with specific parameters, such as encoding.
Get the element node and use SetAttribute to add an attribute to the attribute collection of that element. Create an XmlAttribute node using the CreateAttribute method, get the element node, then use SetAttributeNode to add the node to the attribute collection of that element.
Get the Document Element using getDocumentElement() API method of Document. Create a new Element, using createElement(String tagName ) API method of Document. Append the new node at the end of list of children of the Document Element, with appendChild(Node newChild) API method of Node.
Attributes are part of XML elements. An element can have multiple unique attributes.
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);
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With