Java Core--XML Parsing

Today, I will share with you the practical application of XML parsing. XML is simply a file format. Files in this format are widely used in Java program development, and are generally used as configuration files.

For example, web-related settings need to be configured in web.xml, and any mainstream framework needs to configure the XML file to complete the connection between business logic and the framework system. Of course, if you use SpringBoot, a rapid development framework, you can greatly reduce the configuration of XML files. Generally speaking, XML is used very frequently in development, and it is mainly used for configuration files.


definition


The official definition is Extensible Markup Language, Extensible Markup Language, or XML for short.


Features


1.XML has nothing to do with the development platform of the operating system and programming language.

2. Realize data exchange between different systems.

3.XML document content consists of a series of tag elements.

Label syntax:

<element name attribute name="attribute value">element content</element name>


Precautions


1. Attribute values ​​are enclosed in double quotes.

2. An element can have multiple attributes.

3. The attribute value cannot directly contain <, >, ", ', and it is not recommended to directly contain &.

4.XML tags are case sensitive.

5.XML must have the correct nesting structure.

6. Sibling labels are aligned with indentation.

7. Element names can contain letters, numbers or other characters.

8. Element names cannot start with numbers or punctuation marks.

9. Element names cannot contain spaces.


If <, >, ", ', & must appear in XML tags, we can use escape characters to deal with them.


symbol  escape character
< <
> >
" "
' '
& &


XML case


<?xml version="1.0" encoding="UTF-8"?>
<books>
   <book id="001">
       <author>张三</author>
       <title>Java高级编程</title>
       <description>Java高级编程理论加实践讲解</description>
   </book>
   <book id="002">
       <author>李四</author>
       <title>MySQL数据库</title>
       <description>关系型数据库概述</description>
   </book>
</books>


In actual development, XML files are not complicated. Our focus is to read XML, not to define the structure of XML, as long as we can quickly obtain effective information.


So how do we read XML information through Java programs and modify the XML files?


There are many ways, you can use the native DOM parsing method, but the steps of this method are more complicated. Usually, we will use the third-party open source API, dom4j to complete.


dom4j是一个十分优秀的JavaXML API,具有性能优异、功能强大和极其易使用的特点,它的性能超过了官方的dom解析技术。


下载地址:https://dom4j.github.io/


下载完成,将dom4j的jar文件导入工程即可,非常简单。


接下来,我们使用dom4j对一个保存手机信息的XML文件进行增删改查的操作。


XML:


<?xml version="1.0" encoding="UTF-8"?>
<phone>
   <brand name="华为">
       <type name="Mate10"/>
       <type name="P20"/>
       <type name="畅享6"/>
   </brand>
   <brand name="苹果">
       <type name="iPhoneX"/>
       <type name="iPhone8"/>
   </brand>
   <brand name="小米">
       <type name="Note4"/>
       <type name="MIX2"/>
    </brand>
</phone>


查询操作:


//创建reader对象
SAXReader reader = new SAXReader();
//解析xml文件,转换为document对象
Document document = reader.read("resource/phone.xml");
//获取document的根节点,即phone标签对应的节点
Element root = document.getRootElement();
//通过迭代的方式,层层解析document
Iterator iter = root.elementIterator();
while(iter.hasNext()){
   //获取brand元素对象,即brand标签对应的节点
   Element brand = (Element)iter.next();
   //获取brand节点的name属性值,打印
   System.out.println(brand.attributeValue("name"));
   //继续迭代,获取brand的子节点type节点
   Iterator iter2 = brand.elementIterator();
   while(iter2.hasNext()){
       //获取type节点的name属性值,打印
       Element type = (Element)iter2.next();
       System.out.println(type.attributeValue("name"));
   }
}


查询结果:



添加操作:


SAXReader reader = new SAXReader();
Document document = reader.read("resource/phone.xml");
Element root = document.getRootElement();
//给根节点添加brand节点
Element brand = root.addElement("brand");
//给brand节点添加name属性
brand.addAttribute("name", "三星");
//给brand节点添加type节点
Element type = brand.addElement("type");
//给type节点添加name属性
type.addAttribute("name", "S9");
//将document对象保存到xml文件中
//设置编码
OutputFormat of = OutputFormat.createCompactFormat();
of.setEncoding("utf-8");
//获取输出流对象
FileOutputStream fs = new FileOutputStream("resource/phone.xml");
//获取XMLWriter对象
XMLWriter xw = new XMLWriter(fs, of);
//调用write方法写入到xml文件
xw.write(document);
//关闭资源
xw.close();


添加完成,XML:



更新操作:


SAXReader reader = new SAXReader();
Document document = reader.read("resource/phone.xml");
Element root = document.getRootElement();
Iterator iter = root.elementIterator();
int i = 1;
while(iter.hasNext()){
   Element brand = (Element)iter.next();
   //循环遍历,给每一个brand节点添加id属性
   brand.addAttribute("id", i+"");
   i++;
}
//将document对象保存到xml文件中
//设置编码
OutputFormat of = OutputFormat.createCompactFormat();
of.setEncoding("utf-8");
//获取输出流对象
FileOutputStream fs = new FileOutputStream("resource/phone.xml");
//获取XMLWriter对象
XMLWriter xw = new XMLWriter(fs, of);
//调用write方法写入到xml文件
xw.write(document);
//关闭资源
xw.close();


更新完成,XML:



删除操作:


SAXReader reader = new SAXReader();
Document document = reader.read("resource/phoneInfo.xml");
Element root = document.getRootElement();
Iterator iter = root.elementIterator();
while(iter.hasNext()){
   Element brand = (Element)iter.next();
   //删除brand为三星的节点
   if(brand.attributeValue("name").equals("三星")){
       brand.getParent().remove(brand);
   }
}
//将document对象保存到xml文件中
//设置编码
OutputFormat of = OutputFormat.createCompactFormat();
of.setEncoding("utf-8");
//获取输出流对象
FileOutputStream fs = new FileOutputStream("resource/phone.xml");
//获取XMLWriter对象
XMLWriter xw = new XMLWriter(fs, of);
//调用write方法写入到xml文件
xw.write(document);
//关闭资源
xw.close();


删除完成,XML:



以上就是通过dom4j对XML文件进行增删改查的操作,但是实际开发中,我们使用更多的只有查询操作。新增、修改和删除一般都是手动去完成,查询操作结合反射机制去动态处理需求,是XML的常规用法。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324772309&siteId=291194637