import
java.io.File;
import
javax.xml.parsers.DocumentBuilder;
import
javax.xml.parsers.DocumentBuilderFactory;
import
org.w3c.dom.Document;
import
org.w3c.dom.Element;
import
org.w3c.dom.NamedNodeMap;
import
org.w3c.dom.Node;
import
org.w3c.dom.NodeList;
public
class
Demo {
public
static
void
main(String[] args)
throws
Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
File f =
new
File(
"books.xml"
);
Document doc = builder.parse(f);
Element root = doc.getDocumentElement();
NodeList list = root.getElementsByTagName(
"book"
);
for
(
int
i =
0
; i < list.getLength(); i++) {
Element n = (Element) list.item(i);
NamedNodeMap node = n.getAttributes();
for
(
int
x =
0
; x < node.getLength(); x++) {
Node nn = node.item(x);
System.out.println(nn.getNodeName() +
": "
+ nn.getNodeValue());
}
System.out.println(
"title: "
+n.getElementsByTagName(
"title"
).item(
0
).getFirstChild().getNodeValue());
System.out.println(
"author: "
+ n.getElementsByTagName(
"author"
).item(
0
).getFirstChild().getNodeValue());
System.out.println();
}
}
}