package com.xd.test;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();//创建解析器工厂对象
DocumentBuilder db = dbf.newDocumentBuilder();//创建解析器
Document doc = db.parse("src/first.xml");//创建xml文档对象
Element e = (Element) doc.getElementsByTagName("school").item(0);
NodeList n1 = e.getElementsByTagName("grade");
for (int i = 0; i < n1.getLength(); i++) {
Element e1 = (Element) n1.item(i);
NodeList n2 = e.getElementsByTagName("class");
System.out.println("学员姓名\t学员性别\t学员年龄");
for (int k = 0; i < n2.getLength(); i++) {
Element el = (Element) n2.item(i);
NodeList stus = el.getElementsByTagName("student");
for (int j = 0; j < stus.getLength(); j++) {
Element stu = (Element) stus.item(j);
String stuName = stu.getAttribute("name");
String stuSex = stu.getAttribute("sex");
String stuAge = stu.getAttribute("age");
System.out.println(stuName + "\t" + stuSex + "\t"
+ stuAge);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
xml文件
<?xml version="1.0" encoding="UTF-8"?>
<school>
<grade name="一年级">
<class name="一班">
<student name="三毛" sex="男" age="20" />
<student name="小强" sex="男" age="20" />
<student name="小红" sex="女" age="20" />
</class>
<class name="二班">
<student name="三毛" sex="男" age="20" />
<student name="小强" sex="男" age="20" />
<student name="小红" sex="女" age="20" />
</class>
</grade>
<grade name="二年级">
<class name="一班">
<student name="三毛" sex="男" age="20" />
<student name="小强" sex="男" age="20" />
<student name="小红" sex="女" age="20" />
</class>
<class name="二班">
<student name="三毛" sex="男" age="20" />
<student name="小强" sex="男" age="20" />
<student name="小红" sex="女" age="20" />
</class>
</grade>
<grade name="三年级">
<class name="一班">
<student name="三毛" sex="男" age="20" />
<student name="小强" sex="男" age="20" />
<student name="小红" sex="女" age="20" />
</class>
<class name="二班">
<student name="三毛" sex="男" age="20" />
<student name="小强" sex="男" age="20" />
<student name="小红" sex="女" age="20" />
</class>
</grade>
</school>