Java使用DOM读取XML数据<?xml version="1.0" encoding="GB2312" standalone="no"?> <PhoneInfo> <Brand name="Apple"> <Type name="iPhone4" /> <Type name="iPhone5" /> </Brand> <Brand name="华为"> <Type name="U8650" /> </Brand> <Brand name="华为"> <Type name="U8890" /> </Brand> </PhoneInfo>
时间: 2023-07-19 18:04:02 浏览: 90
Java用DOM4J读取XML
可以使用Java的DOM(文档对象模型)来读取XML数据。
首先,需要导入相关的包:
```java
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
```
然后,可以使用以下代码来读取XML数据:
```java
try {
//创建DocumentBuilderFactory对象
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//创建DocumentBuilder对象
DocumentBuilder builder = factory.newDocumentBuilder();
//读取XML文件
Document document = builder.parse("phone.xml");
//获取根元素
Element root = document.getDocumentElement();
//获取Brand元素列表
NodeList brandList = root.getElementsByTagName("Brand");
for (int i = 0; i < brandList.getLength(); i++) {
Element brand = (Element) brandList.item(i);
String brandName = brand.getAttribute("name");
System.out.println("Brand: " + brandName);
//获取Type元素列表
NodeList typeList = brand.getElementsByTagName("Type");
for (int j = 0; j < typeList.getLength(); j++) {
Element type = (Element) typeList.item(j);
String typeName = type.getAttribute("name");
System.out.println("Type: " + typeName);
}
}
} catch (Exception e) {
e.printStackTrace();
}
```
运行以上代码,可以得到以下输出:
```
Brand: Apple
Type: iPhone4
Type: iPhone5
Brand: 华为
Type: U8650
Brand: 华为
Type: U8890
```
这样就可以通过Java的DOM来读取XML数据了。
阅读全文