Java解析XML的四種方式

xml文件

<?xml version="1.0" encoding="utf-8" ?>
<class>
    <student>
        <firstname>cxx1</firstname>
        <lastname>Bob1</lastname>
        <nickname>stars1</nickname>
        <marks>85</marks>
    </student>
    <student rollno="493">
        <firstname>cxx2</firstname>
        <lastname>Bob2</lastname>
        <nickname>stars2</nickname>
        <marks>85</marks>
    </student>
    <student rollno="593">
        <firstname>cxx3</firstname>
        <lastname>Bob3</lastname>
        <nickname>stars3</nickname>
        <marks>85</marks>
    </student>
</class>

1.DOM方式

package com.cxx.xml;

import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
/**
 * @Author: cxx
 * Dom操作xml
 * @Date: 2018/5/29 20:19
 */
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();
        }
    }
}

結果截圖

2.SAX方式

package com.cxx.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;

/**
 * @Author: cxx
 * SAX解析DOM
 * 一行一行  Handler
 * startElement
 * endElement
 * @Date: 2018/5/29 20:03
 */
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);
        }
    }
}

結果截圖

3.JDOM方式

<!--jdom -->
<dependency>
    <groupId>org.jdom</groupId>
    <artifactId>jdom</artifactId>
    <version>1.1.3</version>
</dependency>
package com.cxx.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;
/**
 * @Author: cxx
 * JDom解析xml
 * 快速開發XML應用程序。
 * 是一個開源項目
 * JDOM主要用來彌補DOM和SAX在實際應用當中的不足。
 * @Date: 2018/5/30 11:44
 */
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======");
        }
    }
}

結果截圖

4.DOM4J方式

 <!-- dom4j -->
 <dependency>
     <groupId>dom4j</groupId>
     <artifactId>dom4j</artifactId>
     <version>1.6.1</version>
</dependency>
package com.cxx.xml;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

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

/**
 * @Author: cxx
 * Dom4j解析xml
 * @Date: 2018/5/30 12:21
 */
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());
            }
        }
    }
}

總結

到此這篇關於Java解析XML的四種方式的文章就介紹到這瞭。希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: