public class TestXML {
public static void main(String[] args) throws SAXException, IOException {
//Dom方式解析XML
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse("books.xml");
NodeList bookList = document.getElementsByTagName("book");
System.out.println("一共有"+bookList.getLength()+"本书");
for (int i = 0; i < bookList.getLength(); i++) {
Node node = bookList.item(i);
NamedNodeMap attrs = node.getAttributes();
System.out.println("第"+(i+1)+"本书共有"+attrs.getLength()+"个属性");
for (int j = 0; j < attrs.getLength(); j++) {
Node attr = attrs.item(j);
System.out.print("属性名:"+attr.getNodeName());
System.out.println("--属性值:"+attr.getNodeValue());
}
NodeList child = node.getChildNodes();
for (int j = 0; j < child.getLength(); j++) {
if(child.item(j).getNodeType()==Node.ELEMENT_NODE)
System.out.println(child.item(j).getNodeName()+":"+child.item(j).getTextContent());
}
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
}
}
Jumping from failure to failure with undiminished enthusiasm is the big secret to success.