java解析这段xml:<?xml version="1.0" encoding="UTF-8"?><bookstore> <book category="children"> <title lang="en">Harry Potter</title> <author>J.K. Rowling</author> <year>2005</year> <price>29.99</price> </book> <book category="web"> <title lang="en">Learning XML</title> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</price> </book></bookstore>
时间: 2023-06-26 09:07:26 浏览: 186
JAVA 解析xml
5星 · 资源好评率100%
可以使用Java中的DOM(文档对象模型)解析器来解析XML文档。
以下是一个示例代码,它使用DOM解析器来解析上述XML文档,并输出每个书籍的标题、作者、年份和价格:
```java
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
public class XMLParser {
public static void main(String[] args) {
try {
// 创建DOM解析器工厂
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// 创建DOM解析器
DocumentBuilder builder = factory.newDocumentBuilder();
// 解析XML文档
Document doc = builder.parse("bookstore.xml");
// 获取所有book元素
NodeList bookList = doc.getElementsByTagName("book");
// 遍历book元素
for (int i = 0; i < bookList.getLength(); i++) {
Element book = (Element) bookList.item(i);
// 获取title元素
Element title = (Element) book.getElementsByTagName("title").item(0);
// 获取author元素
Element author = (Element) book.getElementsByTagName("author").item(0);
// 获取year元素
Element year = (Element) book.getElementsByTagName("year").item(0);
// 获取price元素
Element price = (Element) book.getElementsByTagName("price").item(0);
// 输出书籍信息
System.out.println("Title: " + title.getTextContent());
System.out.println("Author: " + author.getTextContent());
System.out.println("Year: " + year.getTextContent());
System.out.println("Price: " + price.getTextContent());
System.out.println("==============================");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
输出结果如下:
```
Title: Harry Potter
Author: J.K. Rowling
Year: 2005
Price: 29.99
==============================
Title: Learning XML
Author: Erik T. Ray
Year: 2003
Price: 39.95
==============================
```
阅读全文