DOM4J-解析XML
目录
官网详细文档
理解
官网文档好好看,例子等都写的非常棒了,下面仅仅写下自己的理解,便于后期忘记了快速入门
先构建个XML如下:
public static void main(String[] args) throws IOException {
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");
//Document ->String(XML format)
log.info(document.asXML());
}
<?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>
1. Element,Attribute,Text理解
Element: | 例如 <root> ,<author> 这都称为 Element |
Attribute: | 例如<author> 节点里面的参数name ,location 都称为Attribute |
Text: | 例如<author> 节点里面的文本值James Strachan ,Bob McWhirter 都称为Text |
2. Document,String互转
Document ->String
Document document = …;
String text = document.asXML();
String(XML格式的String)转成Document
String text = "<person> <name>James</name> </person>";
Document document = DocumentHelper.parseText(text);
最后,更多使用的例子,可以下载源码后,导入到IDEA中查看
github下载地址:https://github.com/dom4j/dom4j
注意:DOM4J项目使用的是Gradle
,导致项目时选择Gradle
谷歌再多的博客,不如看下源码test下的代码好