使用java解析XML文件的步骤
以前的时候,也解析过,今天又拿出来解析就让忘记怎么解析了,后来在网上查还有自己想,终于解析出来了,下面就是原XML文件:
accp.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE accp SYSTEM "accp.dtd">
<?xml-stylesheet type="text/css" href="accp.css"?>
<accp>
<teachers>
<teacher >
<name>刘老师</name>
<age>30</age>
<degree>硕士</degree>
<position>Java</position>
</teacher>
<teacher>
<name>李老师</name>
<age>28</age>
<degree>本科</degree>
<position>.Net</position>
</teacher>
</teachers>
<students>
<student>
<name>高胜寒</name>
<age>21</age>
<grade>Y2</grade>
<school>北京中心</school>
</student>
<student>
<name>信达雅</name>
<age>19</age>
<grade>S2</grade>
<school>天津中心</school>
</student>
</students>
</accp>
还需要一个dtd文件accp.dtd:
<!ELEMENT accp (teachers,students)>
<!ELEMENT teachers (teacher*)>
<!ELEMENT students (student*)>
<!ELEMENT teacher (name,age,degree,position)>
<!ELEMENT student (name,age,grade,school)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT age (#PCDATA)>
<!ELEMENT degree (#PCDATA)>
<!ELEMENT position (#PCDATA)>
<!ELEMENT grade (#PCDATA)>
<!ELEMENT school (#PCDATA)>
最后就是解析的代码了:
//解析xml文件
public static void Test1(){
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//从DOM工厂获得DOM解析器
try {
DocumentBuilder db = dbf.newDocumentBuilder();
//解析文档,得到一个dom树
Document doc = db.parse("accp.xml");
//得到所有的teacher节点
NodeList teaList = doc.getElementsByTagName("teacher");
System.out.println("xml里面共有"+teaList.getLength()+"个老师信息!");
//循环老师信息
for (int i = 0; i < teaList.getLength(); i++) {
Node teacher = teaList.item(i);
//获取第i个老师的信息的id值并输出
/*Element element = (Element)teacher;
String id = element.getAttribute("id");
System.out.println("id:"+id);*/
//获取第i个老师元素的所有子元素的名称和值并输出
for(Node node=teacher.getFirstChild();node!=null;node =node.getNextSibling() ){
if(node.getNodeType()==Node.ELEMENT_NODE){
String value = node.getFirstChild().getNodeValue();
System.out.print("name:"+value+"\t");
}
}
System.out.println();
}
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
最后看一下运行结果: