Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Updating multiple elements in XML Document with same value

Status
Not open for further replies.

tommyc7

Programmer
Feb 3, 2007
33
US
I need some help using the Java XML APIs.

Suppose I have an org.w3c.dom.Document containing an XML that is similar to:

Code:
<XML>
  <outer>
    <type>A</type>
    <inner>123</inner>
  </outer>
  <outer>
    <type>B</type>
    <inner>123</inner>
  </outer>
  <outer>
    <type>C</type>
    <inner>123</inner>
  </outer>
</XML>

What is the easiest and "best" way to change all of the <inner> values from 123 to 321 (regardless of <type>)?

 
[1] Suppose you have set up and got the org.w3c.dom.Document, say doc, ready to go, you can sure use the getElementsByTagName() method to do this.
[tt]
NodeList onl = doc.getElementsByTagName("inner");
int nnl = onl.getLength();
for (int i=0; i<onl.getLength(); i++){
Node onode = onl.item(i);
onode.getFirstChild().setNodeValue((new StringBuffer(onode.getFirstChild().getNodeValue())).reverse().toString());
}
[/tt]
[2] After that, if you need to persist the change and save it to a file, maybe, you have to appeal to deprecated, but still working well, org.apache.xml.serialize.XMLSerializer to do the job.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top