JAVA中使用DOM解析XML文件
作者:互联网
使用到的工具和软件有:IntelliJ IDEA 各种版本, dom4j-1.6.1, 一个xml文件;
1.查看xml文件的格式,便于后面的模拟输出
<?xml version="1.0" encoding="utf-8" ?> <!DOCTYPE books [ <!ELEMENT books (book+)> <!ELEMENT book (name, author, price)> <!ATTLIST book id CDATA #REQUIRED> <!ELEMENT name (#PCDATA)> <!ELEMENT author (#PCDATA)> <!ELEMENT price (#PCDATA)> ]> <books> <book id="1"> <name>测试1</name> <author>作者1</author> <price>25.0</price> </book> <book id="2"> <name>测试2</name> <author>作者2</author> <price>50</price> </book> <book id="3"> <name>测试3</name> <author>作者3</author> <price>2.5</price> </book> </books>
2.导入dom4j框架包
3.新建Test测试类
4.导入各种包,idea中可在使用时快捷加载 ,所有异常只做抛出不做处理
1 import org.dom4j.Attribute; 2 import org.dom4j.Document; 3 import org.dom4j.DocumentException; 4 import org.dom4j.Element; 5 import org.dom4j.io.SAXReader; 6 import java.io.File; 7 import java.lang.reflect.InvocationTargetException; 8 import java.util.Iterator;
5.创建StringBuilder对象,用于模拟输出,实例化SAXReader类
//不做异常处理 只抛出 public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, DocumentException {
//创建StringBuilder对象,收集数据信息 StringBuilder sb = new StringBuilder(); //加载SAXReader类 Class<?> cf = Class.forName("org.dom4j.io.SAXReader"); //实例化SAXReader类 SAXReader sr = (SAXReader)cf.getDeclaredConstructor().newInstance();
6.读取books.xml节点信息
//SAXReader的read() 读取 books.xml Document bdoc = sr.read(new File("src/com/test/dom/domain/books.xml")); //getRootElement() 拿到根节点信息 Element rootElement = bdoc.getRootElement(); //elementIterator 拿到根节点的子节点信息 Iterator<Element> biter = rootElement.elementIterator();
7.拼接数据信息 模拟输出文档原本信息
//hasNext判断是否存在下一个元素 while (biter.hasNext()) { //next()指针下移,返回该指针所指向的元素 Element next = biter.next(); Attribute id = next.attribute("id"); //拼接<book id = "1"> sb.append("<"); //拿到book sb.append(next.getName()); sb.append(" "); //拿到key值 'id' sb.append(id.getName()); sb.append("="); //拿到value值 '1' sb.append(id.getValue()); sb.append(">"); //拿到book下的子节点信息 Iterator<Element> iter = next.elementIterator(); sb.append("\n"); while(iter.hasNext()) { //拼接 //<name> </name> //<author></author> //<price></price> Element next1 = iter.next(); sb.append("\t"); sb.append("<"); sb.append(next1.getName()); sb.append(">"); sb.append(next1.getStringValue()); sb.append("<"); sb.append("/"); sb.append(next1.getName()); sb.append(">"); sb.append("\n"); } //拼接</book> sb.append("<"); sb.append("/"); sb.append(next.getName()); sb.append(">"); sb.append("\n"); }
8. 输出StringBuilder信息
//输出信息 System.out.println(sb);
线程安全:StringBuffer线程安全,StringBuilder线程不安全。缓冲区:StringBuffer直接使用toStringCache构造字符串。StringBuilder复制字符数组再构造。性能:StringBuilder的性能要远大于StringBuffer。
标签:XML,JAVA,DOM,SAXReader,StringBuilder,dom4j,import,sb,append 来源: https://www.cnblogs.com/zhuimu/p/14276302.html