DOM读取XML文件

时间:2022-08-03 12:05:53

创建XML文件:

<?xml version="1.0" encoding="utf-8"?>
<bookstore>
<!--记录书本的信息 -->
<book Type="必修课">
<title>数据结构</title>
<author>张三</author>
<price>30.00</price>
</book>
<book Type="必修课" >
<title>java基础</title>
<author>李四</author>
<price>40.00</price>
</book>
<book Type="必修课" >
<title>计算机组成原理</title>
<author>王五</author>
<price>50.00</price>
</book>
<book Type="必修课">
<title>软件质量保证与管理</title>
<author>赵六</author>
<price>60.00</price>
</book>
<book Type="必修课" >
<title>算法设计与分析</title>
<author>李七</author>
<price>70.00</price>
</book>
</bookstore>

工厂模式进行XML解析:

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;


public class DOMReadXML {

public static void main(String[] args) {


try{

File file = new File("XmlDemo.xml");

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

DocumentBuilder builder = factory.newDocumentBuilder();

Document doc = builder.parse(file);

NodeList nl = doc.getElementsByTagName("book");

for(int i=0; i<nl.getLength();i++){

System.out.print("书名:"+ doc.getElementsByTagName("title").item(i).getFirstChild().getNodeValue());
System.out.println("作者:"+ doc.getElementsByTagName("author").item(i).getFirstChild().getNodeValue());
System.out.println("价格:"+ doc.getElementsByTagName("price").item(i).getFirstChild().getNodeValue());
}




}catch (Exception e) {
e.printStackTrace();
}
}
}

运行结果:
DOM读取XML文件