dom4j与string

2022/3/25 6:22:39

本文主要是介绍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;
    }
}


这篇关于dom4j与string的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程