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
how to add an attribute to an XML element
提问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 value
field under the type
field, I have to fill in the action
attribute in the type
field. I am a bit stumped. I am able to get the value of the value
field, 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 type
Element
before you traverse to its value
child. (assuming you visited it already).
要返回,只需type
Element
在遍历其value
子项之前保存对 的引用。(假设您已经访问过它)。
to change the value, use the setAttribute()method.
要更改值,请使用setAttribute()方法。
edit:
编辑:
Alternate method: from the value
text 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");
}