java解析XML有很多方式,dom4j jdom等等。
今天发现org.w3c.dom 是java自带的类包。而且比较简单
/*
java解析XML,读取xml中的书名和作者
*/
package com.javaer.examples.file;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.*;
public class ReadXML {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
Document doc = db.parse(new File("/Users/mc2/WEB/JSP/Javaer/x1.xml"));
Element elmtInfo = doc.getDocumentElement();
NodeList nodes = elmtInfo.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
// System.out.println(node.getNodeName());
NodeList nodes2 = node.getChildNodes();
for (int j = 0; j < nodes2.getLength(); j++) {
Node node2 = nodes2.item(j);
if (node2.getNodeType() == Node.ELEMENT_NODE) {
System.out.println(node2.getNodeName() + " : "
+ node2.getTextContent());
}
}
}
}
}
}
xml
English study
James.bangding
Gargon Goyui
Tomas.Tang
执行结果
name : English study
author : James.bangding
name : Gargon Goyui
author : Tomas.Tang