<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="students.xsl"?>
<students>
<student sn="01">
<name>张三</name>
<age>18</age>
</student>
<student sn="02">
<name>李四</name>
<age>20</age>
</student>
</students>
package hotbox.smis.util;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class ReadXML {
/**
* @param args
*/
public static void main(String[] args) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
System.out.println(dbf.getClass().getName());
try {
DocumentBuilder db = dbf.newDocumentBuilder();
// 读取文件
Document doc = db.parse(new File("src/menu.xml"));
// 获取子节点
NodeList nl = doc.getElementsByTagName("student");
int len = nl.getLength();
// 获取节点数
System.out.println(len);
for (int i = 0; i < len; i++) {
Element eltStu = (Element) nl.item(i);
Node eltName = eltStu.getElementsByTagName("name").item(0);
Node eltAge = eltStu.getElementsByTagName("age").item(0);
String name = eltName.getFirstChild().getNodeValue();
String age = eltAge.getFirstChild().getNodeValue();
System.out.println("name: " + name);
System.out.println("age: " + age);
System.out.println("-------------------------");
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}