ridermule
ridermule

Reputation: 143

how to add an attribute to an XML element

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!

Upvotes: 4

Views: 10957

Answers (2)

Seismoid
Seismoid

Reputation: 146

try something like

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

Upvotes: 1

Colin D
Colin D

Reputation: 5661

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.

Upvotes: 4

Related Questions