Four methods take you to parse xml files and xml strings

The first type: Dom4j analysis

Advantage
1. It is an intelligent branch of JDom, which incorporates many functions beyond the basic XML document representation.
2. Dom4j uses interfaces and abstract basic class methods, which is an excellent Java XML API.
3. It has the characteristics of excellent performance, good flexibility, powerful functions and extremely easy to use.
4. Open source code.
Add maven

<dependency>
     <groupId>dom4j</groupId>
     <artifactId>dom4j</artifactId>
     <version>1.6.1</version>
</dependency>

(1) Parse the xml file and prepare to parse the data (when testing, pay attention to the location of the file)

<?xml version="1.0" encoding="utf-8" ?>
<class>
    <student>
        <name>Gaoj</name>
        <class></class>
        <sex>male</sex>
        <age>27</age>
    </student>
</class>

Analyze the demo

package com.test.xml;

import org.dom4j.*;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.Iterator;
import java.util.List;

public class Dom4JDemo {
    public static void main(String[] args) throws Exception {
        //1.创建Reader对象
        SAXReader reader = new SAXReader();
        //2.加载xml
        Document document = reader.read(new File("src/main/resources/demo.xml"));
        //3.获取根节点
        Element rootElement = document.getRootElement();
        Iterator iterator = rootElement.elementIterator();
        while (iterator.hasNext()){
            Element stu = (Element) iterator.next();
            List<Attribute> attributes = stu.attributes();
            System.out.println("======获取属性值======");
            for (Attribute attribute : attributes) {
                System.out.println(attribute.getValue());
            }
            System.out.println("======遍历子节点======");
            Iterator iterator1 = stu.elementIterator();
            while (iterator1.hasNext()){
                Element stuChild = (Element) iterator1.next();
                System.out.println("节点名:"+stuChild.getName()+"---节点值:"+stuChild.getStringValue());
            }
        }
    }
}

(2) Parse the string of xml type . The analytical data is given in the program.

package com.test.xml;

import org.dom4j.*;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.Iterator;
import java.util.List;

public class Dom4JDemo {
    public static void main(String[] args) throws Exception {
        //1.创建Reader对象
        SAXReader reader = new SAXReader();
        //2.加载xml
        Document document  = null;
        try {
            document  = DocumentHelper.parseText("<?xml version=\"1.0\" encoding=\"utf-8\" ?><class><student><firstname>cxx1</firstname><lastname>Bob1</lastname><nickname>stars1</nickname><marks>85</marks></student></class>");
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        //3.获取根节点
        Element rootElement = document.getRootElement();
        Iterator iterator = rootElement.elementIterator();
        while (iterator.hasNext()){
            Element stu = (Element) iterator.next();
            List<Attribute> attributes = stu.attributes();
            System.out.println("======获取属性值======");
            for (Attribute attribute : attributes) {
                System.out.println(attribute.getValue());
            }
            System.out.println("======遍历子节点======");
            Iterator iterator1 = stu.elementIterator();
            while (iterator1.hasNext()){
                Element stuChild = (Element) iterator1.next();
                System.out.println("节点名:"+stuChild.getName()+"---节点值:"+stuChild.getStringValue());
            }
        }
    }
}

The second type: Dom analysis

Advantages
1. A tree structure is formed, which is intuitive and easy to understand, and the code is easier to write.
2. The tree structure is kept in the memory during the parsing process for easy modification.
Disadvantages
1. When the xml file is large, the memory consumption is relatively large, which easily affects the parsing performance and causes memory overflow.
(1) Parse the xml file and prepare to parse the data (when testing, pay attention to the location of the file)

<?xml version="1.0" encoding="utf-8" ?>
<class>
    <student>
        <name>Gaoj</name>
        <class></class>
        <sex>male</sex>
        <age>27</age>
    </student>
</class>

Analyze the demo

package com.test.xml;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;


public class DomDemo {
    //用Element方式
    public static void element(NodeList list){
        for (int i = 0; i <list.getLength() ; i++) {
            Element element = (Element) list.item(i);
            NodeList childNodes = element.getChildNodes();
            for (int j = 0; j <childNodes.getLength() ; j++) {
                if (childNodes.item(j).getNodeType()==Node.ELEMENT_NODE) {
                    //获取节点
                    System.out.print(childNodes.item(j).getNodeName() + ":");
                    //获取节点值
                    System.out.println(childNodes.item(j).getFirstChild().getNodeValue());
                }
            }
        }
    }

    public static void node(NodeList list){
        for (int i = 0; i <list.getLength() ; i++) {
            Node node = list.item(i);
            NodeList childNodes = node.getChildNodes();
            for (int j = 0; j <childNodes.getLength() ; j++) {
                if (childNodes.item(j).getNodeType()==Node.ELEMENT_NODE) {
                    System.out.print(childNodes.item(j).getNodeName() + ":");
                    System.out.println(childNodes.item(j).getFirstChild().getNodeValue());
                }
            }
        }
    }

    public static void main(String[] args) {
        //1.创建DocumentBuilderFactory对象
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        //2.创建DocumentBuilder对象
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document d = builder.parse("src/main/resources/demo.xml");
            NodeList sList = d.getElementsByTagName("student");
            //element(sList);
            node(sList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The third type: JDom analysis

Advantages
1. Only use concrete classes without using interfaces.
2. The API makes extensive use of the Collections class.
Add maven

<dependency>
    <groupId>org.jdom</groupId>
    <artifactId>jdom</artifactId>
    <version>1.1.3</version>
</dependency>

**(1) Parse the xml file** Prepare to parse the data (when testing, pay attention to the location of the file)

<?xml version="1.0" encoding="utf-8" ?>
<class>
    <student>
        <name>Gaoj</name>
        <class></class>
        <sex>male</sex>
        <age>27</age>
    </student>
</class>

Analyze the demo

package com.test.xml;

import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;

public class JDomDemo {
    public static void main(String[] args) throws Exception {
        //1.创建SAXBuilder对象
        SAXBuilder saxBuilder = new SAXBuilder();
        //2.创建输入流
        InputStream is = new FileInputStream(new File("src/main/resources/demo.xml"));
        //3.将输入流加载到build中
        Document document = saxBuilder.build(is);
        //4.获取根节点
        Element rootElement = document.getRootElement();
        //5.获取子节点
        List<Element> children = rootElement.getChildren();
        for (Element child : children) {
            System.out.println("通过rollno获取属性值:"+child.getAttribute("rollno"));
            List<Attribute> attributes = child.getAttributes();
            //打印属性
            for (Attribute attr : attributes) {
                System.out.println(attr.getName()+":"+attr.getValue());
            }
            List<Element> childrenList = child.getChildren();
            System.out.println("======获取子节点-start======");
            for (Element o : childrenList) {
                System.out.println("节点名:"+o.getName()+"---"+"节点值:"+o.getValue());
            }
            System.out.println("======获取子节点-end======");
        }
    }
}

**(2) Parsing xml type string test data is given in the program

package com.test.xml;

import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import java.io.*;
import java.util.List;

public class JDomDemo {
    public static void main(String[] args) throws Exception {
        //1.创建SAXBuilder对象
        SAXBuilder saxBuilder = new SAXBuilder();
        java.io.Reader in = new StringReader("<?xml version=\"1.0\" encoding=\"utf-8\" ?><class><student><firstname>cxx1</firstname><lastname>Bob1</lastname><nickname>stars1</nickname><marks>85</marks></student></class>");
        Document document = (new SAXBuilder()).build(in);
        //4.获取根节点
        Element rootElement = document.getRootElement();
        //5.获取子节点
        List<Element> children = rootElement.getChildren();
        for (Element child : children) {
            System.out.println("通过rollno获取属性值:"+child.getAttribute("rollno"));
            List<Attribute> attributes = child.getAttributes();
            //打印属性
            for (Attribute attr : attributes) {
                System.out.println(attr.getName()+":"+attr.getValue());
            }
            List<Element> childrenList = child.getChildren();
            System.out.println("======获取子节点-start======");
            for (Element o : childrenList) {
                System.out.println("节点名:"+o.getName()+"---"+"节点值:"+o.getValue());
            }
            System.out.println("======获取子节点-end======");
        }
    }
}

Fourth: Sax analysis

Advantages
1. Using event-driven mode, the memory consumption is relatively small.
2. Applicable when only processing data in xml.
Disadvantages
1. Not easy to code.
2. It is difficult to access multiple different data in the same xml at the same time.
(1) Parse the xml file and prepare to parse the data (when testing, pay attention to the location of the file)

<?xml version="1.0" encoding="utf-8" ?>
<class>
    <student>
        <name>Gaoj</name>
        <class></class>
        <sex>male</sex>
        <age>27</age>
    </student>
</class>

Analyze the demo

package com.test.xml;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

public class SaxDemo {

    public static void main(String[] args) throws Exception {
        //1.或去SAXParserFactory实例
        SAXParserFactory factory = SAXParserFactory.newInstance();
        //2.获取SAXparser实例
        SAXParser saxParser = factory.newSAXParser();
        //创建Handel对象
        SAXDemoHandel handel = new SAXDemoHandel();
        saxParser.parse("src/main/resources/demo.xml",handel);
    }
}

class SAXDemoHandel extends DefaultHandler {
    //遍历xml文件开始标签
    @Override
    public void startDocument() throws SAXException {
        super.startDocument();
        System.out.println("sax解析开始");
    }

    //遍历xml文件结束标签
    @Override
    public void endDocument() throws SAXException {
        super.endDocument();
        System.out.println("sax解析结束");
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        super.startElement(uri, localName, qName, attributes);
        if (qName.equals("student")){
            System.out.println("============开始遍历student=============");
            //System.out.println(attributes.getValue("rollno"));
        }
        else if (!qName.equals("student")&&!qName.equals("class")){
            System.out.print("节点名称:"+qName+"----");
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        super.endElement(uri, localName, qName);
        if (qName.equals("student")){
            System.out.println(qName+"遍历结束");
            System.out.println("============结束遍历student=============");
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        super.characters(ch, start, length);
        String value = new String(ch,start,length).trim();
        if (!value.equals("")) {
            System.out.println(value);
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_44962429/article/details/104620216