假设我们有一个名为“books.xml”的XML文件,它包含以下内容:
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
</catalog>
解析示例代码为:
import javax.xml.parsers.DocumentBuilderFactory; //导入解析XML所需的类库
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
import java.io.File;
public class ReadXMLFile {
public static void main(String argv[]) { //主函数开始
try { //使用try-catch语句捕捉异常
File fXmlFile = new File("books.xml"); //创建一个名为“books.xml”的File对象
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); //创建DocumentBuilderFactory对象
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); //创建DocumentBuilder对象
Document doc = dBuilder.parse(fXmlFile); //用DocumentBuilder对象解析“books.xml”文件,得到一个代表整个XML文档的Document对象
doc.getDocumentElement().normalize(); //将文档归一化(可选)
System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); //打印根元素的名称
NodeList nList = doc.getElementsByTagName("book"); //获取所有的“book”元素
System.out.println("----------------------------"); //分割线
for (int temp = 0; temp < nList.getLength(); temp++) { //循环遍历每个“book”元素
Node nNode = nList.item(temp); //获取当前节点
System.out.println("\nCurrent Element :" + nNode.getNodeName()); //打印当前元素的名称
if (nNode.getNodeType() == Node.ELEMENT_NODE) { //如果当前节点是元素节点
Element eElement = (Element) nNode; //将当前节点转换成元素节点
System.out.println("Book id : " + eElement.getAttribute("id")); //打印“book”元素的id属性值
System.out.println("Title : " + eElement.getElementsByTagName("title").item(0).getTextContent()); //打印“book”元素的title子元素内容
System.out.println("Author : " + eElement.getElementsByTagName("author").item(0).getTextContent()); //打印“book”元素的author子元素内容
System.out.println("Price : " + eElement.getElementsByTagName("price").item(0).getTextContent()); //打印“book”元素的price子元素内容
}
}
} catch (Exception e) { //捕捉并处理异常
e.printStackTrace(); //打印异常信息
}
}
}
当我们运行上面的Java程序时,它将输出以下内容:
Root element :catalog
----------------------------
Current Element :book
Book id : bk101
Title : XML Developer's Guide
Author : Gambardella, Matthew
Price : 44.95
Current Element :book
Book id : bk102
Title : Midnight Rain
Author : Ralls, Kim
Price : 5.95