java使用DOM读取XML数据
时间: 2023-09-13 22:05:01 浏览: 77
使用DOM(文档对象模型)读取XML数据需要以下步骤:
1. 创建DocumentBuilderFactory实例
```
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
```
2. 创建DocumentBuilder实例
```
DocumentBuilder builder = factory.newDocumentBuilder();
```
3. 解析XML文件并返回Document对象
```
Document document = builder.parse(new File("example.xml"));
```
4. 获取根节点
```
Element rootElement = document.getDocumentElement();
```
5. 遍历子节点获取需要的信息
```
NodeList nodeList = rootElement.getElementsByTagName("book");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
String title = element.getElementsByTagName("title").item(0).getTextContent();
String author = element.getElementsByTagName("author").item(0).getTextContent();
String price = element.getElementsByTagName("price").item(0).getTextContent();
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.println("Price: " + price);
}
}
```
完整代码示例:
```java
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XMLReader {
public static void main(String[] args) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File("example.xml"));
Element rootElement = document.getDocumentElement();
NodeList nodeList = rootElement.getElementsByTagName("book");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
String title = element.getElementsByTagName("title").item(0).getTextContent();
String author = element.getElementsByTagName("author").item(0).getTextContent();
String price = element.getElementsByTagName("price").item(0).getTextContent();
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.println("Price: " + price);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
阅读全文