其他分享
首页 > 其他分享> > dom4j与string

dom4j与string

作者:互联网

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