java dom4j读取xml文件
时间: 2023-07-11 09:45:29 浏览: 72
首先需要导入dom4j的jar包。然后可以按照以下步骤读取xml文件:
1. 创建SAXReader对象:
```
SAXReader reader = new SAXReader();
```
2. 读取xml文件并返回Document对象:
```
Document document = reader.read(new File("file.xml"));
```
3. 获取根节点:
```
Element root = document.getRootElement();
```
4. 获取子节点:
```
List<Element> childList = root.elements();
```
5. 获取节点属性值:
```
String value = element.attributeValue("attributeName");
```
6. 获取节点文本值:
```
String text = element.getText();
```
完整示例代码如下:
```
import java.io.File;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class Dom4jTest {
public static void main(String[] args) {
try {
// 创建SAXReader对象
SAXReader reader = new SAXReader();
// 读取xml文件并返回Document对象
Document document = reader.read(new File("file.xml"));
// 获取根节点
Element root = document.getRootElement();
// 获取子节点
List<Element> childList = root.elements();
for (Element element : childList) {
// 获取节点属性值
String value = element.attributeValue("attributeName");
// 获取节点文本值
String text = element.getText();
System.out.println("attributeName:" + value + ",text:" + text);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
阅读全文