dom4j与string
dom4j的xml与string相互转换
dom4j的xml格式如下:
String格式
James Strachan Bob McWhirter
xml格式
James Strachan
Bob McWhirter
dom4j的数据类型
属于链表加数组,每个element相当于node节点;element存放元素的是attribute,是list类型。
整个xml属于Document类型,是带编码格式的,解析前需要获取rootelement
document类型
<?xml version="1.0" encoding="UTF-8"?>
James Strachan
Bob McWhirter
element类型
James Strachan
Bob McWhirter
dom4j转换的代码
代码源于官网,做了简单的重组,包括两个部分,生成xml,解析xml成string
public class Document4jTest {
public static void main(String[] args) throws DocumentException {
Document document = Document4jTest.createDocument();
System.out.println(document.asXML());//带格式<?xml version="1.0" encoding="UTF-8"?>
System.out.println(document.getRootElement().asXML());//不带格式
String parsetest = document.getRootElement().asXML();
Map hashmap = new HashMap(parse(parsetest));
System.out.println("res hashmap is:"+JSONArray.toJSON(hashmap));
}
public static Document createDocument() {
Document document = DocumentHelper.createDocument();
Element root = document.addElement("root");
Element author1 = root.addElement("author")
.addAttribute("name", "James")
.addAttribute("location", "UK")
.addText("James Strachan");
Element author2 = root.addElement("author")
.addAttribute("name", "Bob")
.addAttribute("location", "US")
.addText("Bob McWhirter");
return document;
}
public static Map parse(String test) throws DocumentException {
System.out.println("=============xml与string转换");
Document document = DocumentHelper.parseText(test);
Element root = document.getRootElement();
Map res = new HashMap();
List elements = root.elements();
for (Element element : elements) {
List attributes = element.attributes();
for (Attribute attribute : attributes) {
System.out.println(attribute.getName()+":"+attribute.getValue());
res.put(attribute.getName(),attribute.getValue());
}
}
System.out.println("====================");
return res;
}
}