在java中向现有的XML节点添加新属性?
我想向现有的 xml 节点添加一个属性。我不想向我的xml文件添加新元素(新节点),我只想添加一个新属性。我该怎么做?
特别是我尝试了这行代码:
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);
但我得到以下例外:
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)**