向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)**

回答:

在DOM解析器中,这非常容易。获取您的节点,只需使用此功能。

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

然后最后更新您的文档。像这样..

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

以上是 向Java中的现有XML节点添加新属性? 的全部内容, 来源链接: utcz.com/qa/425387.html

回到顶部