标签:xml string dom4j James System println document out
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;
}
}
标签:xml,string,dom4j,James,System,println,document,out 来源: https://www.cnblogs.com/yorkiiz/p/16052891.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。