将新属性添加到java中的现有XML节点? [英] Add new attributes to an existing XML node in java?

查看:158
本文介绍了将新属性添加到java中的现有XML节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在现有的xml节点中添加一个属性。我不想在我的xml文件中添加新元素(新节点),我只想添加一个新属性。我怎么能这样做?

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

但我得到以下异常:

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解析器中它非常简单。得到你的节点,只需使用这个函数。

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

这篇关于将新属性添加到java中的现有XML节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆