将新属性添加到 Java 中的现有 XML 节点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20052871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:42:54  来源:igfitidea点击:

Add new attributes to an existing XML node in java?

javaxmlnodes

提问by user2966458

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?

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

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

采纳答案by subash

in DOM parser it is very easy. get your node and simply use this function.

在 DOM 解析器中,这很容易。获取您的节点并简单地使用此功能。

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

回答by stripybadger

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

您可以使用 xslt 在几行中完成。Oracle 有一个半体面的教程,其中包含所有代码片段http://docs.oracle.com/javase/tutorial/jaxp/xslt/transformingXML.html

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

xslt 的关键位如下所示:

    <xsl:template match="elementToAddNewAttrTo">
        <xsl:attribute name="newAttrName">NewAttrValue</xsl:attribute>
    </xsl:template>

回答by Sergey Tarasov

The easiest and the shortest is to cast the node to org.w3c.dom.Elementand then invoke setAttributeon it:

最简单和最短的是将节点转换为org.w3c.dom.Element,然后在其上调用setAttribute

((Element)aNode).setAttribute("name", "value");

回答by Yeti

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

只有在您已经知道您处理的所有节点都应该是“元素”类型的情况下才使用 try-catch 方法(因此任何其他情况都是“例外”并且应该与代码中断)。