需求说明:用XML文件格式表示以下数据
<?xml version="1.0" encoding="UTF-8"?>
<StudentScore>
<Student name="小明">
<Score score="预计得分89"/>
<Score score="预计得分76"/>
<Student name="小红">
<Score score="预计得分98"/>
<Score score="实际得分87"/>
</Student>
</StudentScore>
public static void main(String[] args) throws Exception {
//1、创建一个工厂对象
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
//2、通过工厂对象获取解析器对象
DocumentBuilder db=dbf.newDocumentBuilder();
//3、使用这个解析器对象获取xml文件
Document doc=db.parse("E:/Program%20Files/DAY24/src/test2/Phones.xml");
//4、使用doc操作xml文件,获取元素名是“Brand”的信息
NodeList b=doc.getElementsByTagName("Brand");
//5、遍历子级节点,获取子级节点
for(int i=0;i<b.getLength();i++) {
Node brand=b.item(i);
Element element=(Element) b.item(i);
String value=element.getAttribute("name");
//获取子级节点列表
NodeList ChildNodes=element.getElementsByTagName("Type");
for(int j=0;j<ChildNodes.getLength();j++) {
Element Childelement=(Element)ChildNodes.item(j);
String Childvalue=Childelement.getAttribute("name");
System.out.println(value+":"+Childvalue);
}
}
}