how to add an attribute to an XML element
Solution 1
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.
Solution 2
try something like
nodelist = doc.getElementsByTagName("value");
for (Element element : nodelist) {
Element parent = element.getParentNode()
parent.setAttribute("action", "attrValue");
}
ridermule
Updated on July 25, 2022Comments
-
ridermule almost 2 years
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 thetype
field, I have to fill in theaction
attribute in thetype
field. I am a bit stumped. I am able to get the value of thevalue
field, but I don't know how to go back and add the attribute.Any help will be appreciated a lot!!!
thanks!
-
Hew Wolff over 11 yearsThe read/modify/write cycle is described well in articles such as Parsing, Modifying, and outputting XML Documents with Java and How to modify XML file in Java.