Java DOM edit: Locate a Node and Change Its Content
//Demo xml file
/*
<?xml version="1.0" standalone="yes"?>
<!DOCTYPE folks [
<!ELEMENT folks (person)*>
<!ELEMENT person (name | phone | email)*>
<!ELEMENT name (#PCDATA | bold)*>
<!ELEMENT phone (#PCDATA)>
<!ELEMENT email (#PCDATA)>
<!ELEMENT bold (#PCDATA)>
]>
<folks>
<person>
<name>Sam Spade</name>
<email>samspade@website.com</email>
</person>
<person>
<name>Sam Diamond</name>
<email>samdiamond@website.com</email>
</person>
<person>
<name>Sam Sonite</name>
<email>samsonite@website.com</email>
</person>
</folks>
*/
public void changeContent(Document doc,String newname,String newemail) {
Element root = doc.getDocumentElement();
NodeList rootlist = root.getChildNodes();
for(int i=0; i<rootlist.getLength(); i++) {
Element person = (Element)rootlist.item(i);
NodeList personlist = person.getChildNodes();
Element name = (Element)personlist.item(0);
NodeList namelist = name.getChildNodes();
Text nametext = (Text)namelist.item(0);
String oldname = nametext.getData();
if(oldname.equals(newname)) {
Element email = (Element)personlist.item(1);
NodeList emaillist = email.getChildNodes();
Text emailtext = (Text)emaillist.item(0);
emailtext.setData(newemail);
}
}
}
Related examples in the same category