dom4j的xml與string相互轉換
dom4j的xml格式如下:
String格式
<root><author name="James" location="UK">James Strachan</author><author name="Bob" location="US">Bob McWhirter</author></root>
xml格式
<root>
<author name="James" location="UK">James Strachan</author>
<author name="Bob" location="US">Bob McWhirter</author>
</root>
dom4j的數據類型
屬於鏈表加數組,每個element相當於node節點;element存放元素的是attribute,是list類型。
整個xml屬於Document類型,是帶編碼格式的,解析前需要獲取rootelement
document類型
<?xml version="1.0" encoding="UTF-8"?>
<root>
<author name="James" location="UK">James Strachan</author>
<author name="Bob" location="US">Bob McWhirter</author>
</root>
element類型
<root>
<author name="James" location="UK">James Strachan</author>
<author name="Bob" location="US">Bob McWhirter</author>
</root>
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<String,String> hashmap = new HashMap<String,String>(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<String, String> parse(String test) throws DocumentException {
System.out.println("=============xml與string轉換");
Document document = DocumentHelper.parseText(test);
Element root = document.getRootElement();
Map<String, String> res = new HashMap<String,String>();
List<Element> elements = root.elements();
for (Element element : elements) {
List<Attribute> 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;
}
}
