how to add an attribute to an XML element

dom, java, parsing, xml

Solution

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

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

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.

Problem

I am using the DOM parser. I have to parse the following 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. Any help will be appreciated a lot!!! thanks!

Original source