java–进阶–1.1–Dom4j–常用api
代码位置
https://gitee.com/DanShenGuiZu/learnDemo/tree/master/Dom4j_learn
1、SAXReader类的方法


/**
* 获取Document 文档
* @param file
* @return org.dom4j.Document
* @author feizhou
* @since 2020/9/6 22:47
*/
public static Document getDocument(File file) throws DocumentException {
// 创建xml解析器
SAXReader saxReader = new SAXReader();
// 加载目标文件
Document doc = saxReader.read(file);
return doc;
}
2、Document接口的方法


package fei.zhou.dom4j_learn.business.demo2;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.File;
public class Test01 {
public static void main(String[] args) throws Exception {
// 创建xml解析器
SAXReader saxReader = new SAXReader();
// 加载目标文件
File file = new File(Test01.class.getResource("/").getPath() + "\\xml\\01.xml");
Document doc = saxReader.read(file);
// 获取根元素
Element rootElement = doc.getRootElement();
System.out.println("根元素名称:" + rootElement.getName());
}
}
输出:
根元素名称:members
3、Element接口的方法
- Element addAttribute(String name, String value)://通过属性名和值添加属性
- Element addComment(String comment)://添加评论
- Element addText(String text)://添加元素标签值
- void add(Attribute attribute)://直接添加属性
- boolean remove(Attribute attribute)://删除属性
- String getText()://获取元素的标签值
- String elementText(String name)://获取元素的标签值
- String getTextTrim()://获取元素的标签值并会忽略文本2端的空白字符
- List attributes(): //获取属性集合
- int attributeCount()://获取属性个数
- Iterator attributeIterator()://获取属性集合迭代器
- String attributeValue(String name)://获取某个属性的值
- Element element(String name)://获取第一个子元素
- List elements()://获取子元素集合
- Iterator elementIterator()://获取子元素集合的迭代器
- boolean isRootElement()://查询是否是根元素
剩下的就是继承他父接口Node的方法了
4、Attribute接口的方法
- getName:获取属性的名字,其实是继承其父接口Node的方法
- getValue:获取属性的值
5、OutputFormat类
- OutputFormat createPrettyPrint()://输出漂亮的格式
- OutputFormat createCompactFormat(): //输出紧凑的格式
- setEncoding(String encoding): //指定输出格式