dom4j解析xml输出成txt
时间: 2023-12-15 11:07:23 浏览: 59
dom4j解析xml.txt
首先需要引入dom4j的相关依赖,然后按照以下步骤进行解析xml并输出成txt:
1. 创建一个Document对象并通过dom4j的SAXReader对xml文件进行解析:
```
SAXReader reader = new SAXReader();
Document document = reader.read(new File("file.xml"));
```
2. 通过XPath表达式获取需要的节点:
```
List<Node> nodes = document.selectNodes("//root/element");
```
3. 遍历节点并将内容输出到txt文件:
```
FileWriter writer = new FileWriter("file.txt");
for (Node node : nodes) {
String text = node.getText();
writer.write(text);
}
writer.close();
```
完整代码如下:
```
import java.io.File;
import java.io.FileWriter;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
public class Dom4jXmlToTxt {
public static void main(String[] args) throws Exception {
SAXReader reader = new SAXReader();
Document document = reader.read(new File("file.xml"));
List<Node> nodes = document.selectNodes("//root/element");
FileWriter writer = new FileWriter("file.txt");
for (Node node : nodes) {
String text = node.getText();
writer.write(text);
}
writer.close();
}
}
```
阅读全文