DOM Utilities
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
public class TestDOM {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
Document document = parser.parse("zooinventory.xml");
Element inventory = document.getDocumentElement();
NodeList animals = inventory.getElementsByTagName("Animal");
System.out.println("Animals = ");
for (int i = 0; i < animals.getLength(); i++) {
String name = DOMUtil.getSimpleElementText((Element) animals.item(i), "Name");
String species = DOMUtil.getSimpleElementText((Element) animals.item(i), "Species");
System.out.println(" " + name + " (" + species + ")");
}
Element foodRecipe = DOMUtil.getFirstElement((Element) animals.item(1), "FoodRecipe");
String name = DOMUtil.getSimpleElementText(foodRecipe, "Name");
System.out.println("Recipe = " + name);
NodeList ingredients = foodRecipe.getElementsByTagName("Ingredient");
for (int i = 0; i < ingredients.getLength(); i++)
System.out.println(" " + DOMUtil.getSimpleElementText((Element) ingredients.item(i)));
}
}
class DOMUtil {
public static Element getFirstElement(Element element, String name) {
NodeList nl = element.getElementsByTagName(name);
if (nl.getLength() < 1)
throw new RuntimeException("Element: " + element + " does not contain: " + name);
return (Element) nl.item(0);
}
public static String getSimpleElementText(Element node, String name) {
Element namedElement = getFirstElement(node, name);
return getSimpleElementText(namedElement);
}
public static String getSimpleElementText(Element node) {
StringBuffer sb = new StringBuffer();
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child instanceof Text)
sb.append(child.getNodeValue());
}
return sb.toString();
}
}
//File: zooinventory.xml
/*<?xml version="1.0" encoding="UTF-8"?>
<Element2>
<Element3 animalClass="mammal">
<Name>A</Name>
<Species>B</Species>
<Habitat>C</Habitat>
<Food>D</Food>
<Temperament>E</Temperament>
<Weight>1</Weight>
</Element3>
<Element3 animalClass="mammal">
<Name>F</Name>
<Species>G</Species>
<Habitat>H</Habitat>
<ElementA>
<Name>I</Name>
<Ingredient>I1</Ingredient>
<Ingredient>I2</Ingredient>
<Ingredient>I2</Ingredient>
</ElementA>
<Temperament>J</Temperament>
<Weight>4</Weight>
</Element3>
</Element2>
*/
Related examples in the same category