how to add an attribute to an XML element

10,740

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");
}
Share:
10,740
ridermule
Author by

ridermule

Updated on July 25, 2022

Comments

  • ridermule
    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 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!

  • Hew Wolff
    Hew Wolff over 11 years
    The 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.