如何将属性添加到XML元素

时间:2022-08-19 19:36:07

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.

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

Any help will be appreciated a lot!!!

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

thanks!

2 个解决方案

#1


4  

To go back, just save a reference to the type Element before you traverse to its value child. (assuming you visited it already).

要返回,只需在遍历其value子元素之前保存对Element类型的引用。 (假设你已经访问过它)。

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.

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

#2


1  

try something like

尝试类似的东西

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

#1


4  

To go back, just save a reference to the type Element before you traverse to its value child. (assuming you visited it already).

要返回,只需在遍历其value子元素之前保存对Element类型的引用。 (假设你已经访问过它)。

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.

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

#2


1  

try something like

尝试类似的东西

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