Java DOM edit: A Method to Find an ID Value and Print the Element Text
//An XML Document with ID Tags on Names
/*
<?xml version="1.0" standalone="yes"?>
<!DOCTYPE folks [
<!ELEMENT folks (person)*>
<!ELEMENT person (name)>
<!ELEMENT name (#PCDATA)>
<!ATTLIST name nick ID #IMPLIED>
]>
<folks>
<person>
<name nick="Al">Alite Quandry</name>
</person>
<person>
<name nick="Fred">Mush Pushkin</name>
</person>
<person>
<name nick="Alvie">Avarine Spraddle</name>
</person>
</folks>
*/
public void findByID(Document doc,String idName) {
Element name = doc.getElementById(idName);
if(name == null) {
System.out.println("There is no element with the ID "
+ idName);
} else {
Text text = (Text)name.getFirstChild();
System.out.println("The ID " + idName
+ " locates the name " + text.getData());
}
}
Related examples in the same category