java 如何向 XML 元素添加属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12806908/
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-10-31 10:18:17  来源:igfitidea点击:

how to add an attribute to an XML element

javaxmlparsingdom

提问by ridermule

I am using the DOM parser. I have to parse the following XML:

我正在使用 DOM 解析器。我必须解析以下 XML:

    <abc>
       <type action="">
          <code>test</code>
          <value>001</value>
       </type>
       <type action="">
          <code>test2</code>
          <value>002</value>
       </type>
    </abc>

so, depending on the valuefield under the typefield, I have to fill in the actionattribute in the typefield. I am a bit stumped. I am able to get the value of the valuefield, but I don't know how to go back and add the attribute.

所以,根据value字段下的type字段,我必须填写字段中的action属性type。我有点难住了。我能够获取该value字段的值,但我不知道如何返回并添加该属性。

Any help will be appreciated a lot!!!

任何帮助将不胜感激!!!

thanks!

谢谢!

回答by Colin D

To go back, just save a reference to the typeElementbefore you traverse to its valuechild. (assuming you visited it already).

要返回,只需typeElement在遍历其value子项之前保存对 的引用。(假设您已经访问过它)。

to change the value, use the setAttribute()method.

要更改值,请使用setAttribute()方法。

edit:

编辑:

Alternate method: from the valuetext node, call getParentNode()twice (once to get back to the value element & once to get back to the type element), then call setAttribute()after you do any necissary casting.

替代方法:从value文本节点调用getParentNode()两次(一次返回 value 元素,一次返回 type 元素),然后setAttribute()在执行任何必要的转换后调用。

回答by Seismoid

try something like

尝试类似的东西

nodelist = doc.getElementsByTagName("value");
for (Element element : nodelist) {
Element parent = element.getParentNode()
parent.setAttribute("action", "attrValue");
}