test

How to add an attribute to an XML element

I use the DOM parser. I need 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> 

therefore, depending on the value field in the type field, I have to fill in the action attribute in the type field. I'm a bit stumped. I can get the value of the value field, but I don’t know how to return and add the attribute.

Any help would be appreciated a lot!

thanks!

+4
source share
2 answers

To return, just save the link to type Element before moving on to its child element value . (if you have already visited it).

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

edit:

Alternative method: from the text value node, call getParentNode() twice (once to return to the value element and once to return to the type element), then call setAttribute() after you have setAttribute() casting.

+4
source

try something like

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

Source: https://habr.com/ru/post/1438738/


All Articles