在文章《JAVA 使用Dom4j 解析XML》中,介绍了使用Dom44j解析XML,比如节点的解析遍历、节点的增加、删除、写入文件等操作,本文我们继续使用dom4j实现xml字符串与xml文件之间的转换。
1.xml文档或节点转换为字符串
public void test5()throws Exception{
//创建SAXReader对象
SAXReader reader = new SAXReader();
//读取文件 转换成Document
Document document = reader.read(new File("C:/s.xml"));
//document转换为String字符串
String documentStr = document.asXML();
System.out.println("document 字符串:" + documentStr);
//获取根节点
Element root = document.getRootElement();
//根节点转换为String字符串
String rootStr = root.asXML();
System.out.println("root 字符串:" + rootStr);
//获取其中student1节点
Element student1Node = root.element("student1");
//student1节点转换为String字符串
String student1Str = student1Node.asXML();
System.out.println("student1 字符串:" + student1Str);
}
XML文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<students>
<student1 id="001">
<微信公众号>@残缺的孤独</微信公众号>
<学号>20140101</学号>
<地址>北京海淀区</地址>
<座右铭>要么强大,要么听话</座右铭>
</student1>
<student2 id="002">
<新浪微博>@残缺的孤独</新浪微博>
<学号>20140102</学号>
<地址>北京朝阳区</地址>
<座右铭>在哭泣中学会坚强</座右铭>
</student2>
</students>
2.xml字符串转换为Document对象
public void test6()throws Exception{
String xmlStr = "<employee><empname>@残缺的孤独</empname><age>25</age><title>软件开发工程师</title></employee>";
Document document = DocumentHelper.parseText(xmlStr);
//写入emp1.xml文件
writerDocumentToNewFile(document);
}
3.使用dom4j新建document对象,并写入文件中
public void test7()throws Exception{
Document document = DocumentHelper.createDocument();
Element rootElement = document.addElement("employee");
Element empName = rootElement.addElement("empname");
empName.setText("@残缺的孤独");
Element empAge = rootElement.addElement("age");
empAge.setText("25");
Element empTitle = rootElement.addElement("title");
empTitle.setText("软件开发工程师");
//写入文档emp.xml
writerDocumentToNewFile(document);
}