Java之解析xml的方式大全

书欣 Java面经 发布时间:2023-06-30 10:40:34 阅读数:4528 1
下文笔者讲述四种解析XML的方法
学习完本篇之后,你将彻底掌握Java中xml的解析方法,如下所示

xml简介

 
XML是一种通用的数据交换格式
   它的平台无关性、语言无关性、系统无关性
   常用于不同平台之间数据传输

xml示例分享

<?xml version="1.0" encoding="UTF-8"?>
<persons>
    <person id="1">
        <name>lee</name>
        <age>16</age>
        <call>1001</call>
        <language>Chinese</language>
    </person>
    <person id="2" sex="man">
        <name>cerish</name>
        <age>18</age>
        <call>1002</call>
        <language>English</language>
    </person>
</persons>
 
方式1:
   DOM解析(java提供)
方式2:
   SAX解析(java提供)
方式3:
   JDOM解析(第三方提供)
方式4:
   DOM4J解析(第三方提供)

1.DOM解析(java提供)

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.Nodelist;

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

public class XMLDOMParseTest {
    public static void main(String[] args) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document = db.parse("./information.xml");
            NodeList personList = document.getElementsByTagName("person");
            System.out.println("一共有" + personList.getLength() + "个人");
            for (int i = 0; i < personList.getLength(); i++) {
                System.out.println("================== 开始遍历第" + (i+1) +"个人信息 =================");
                Node person = personList.item(i);
                /* person 的属性遍历 */
                NamedNodeMap attributes = person.getAttributes();
                for (int j = 0; j < attributes.getLength(); j++) {
                    Node attribute = attributes.item(j);
                    System.out.println("\t 属性名: " + attribute.getNodeName() + "\t 属性值:" + attribute.getNodeValue());
                }
                /* person 的子节点遍历 */
                NodeList childNodes = person.getChildNodes();
                for (int k = 0; k < childNodes.getLength(); k++) {
                    Node child = childNodes.item(k);
                    if (child.getNodeType() == Node.ELEMENT_NODE) {
                        System.out.println("\t 子节点: " + child.getNodeName() + "\t 属性值:" + child.getFirstChild().getNodeValue());
                    }
                }
                System.out.println("================== 结束遍历第" + i +"个人信息 =================");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2.SAX解析(java提供)

1.建立一个 Person 类与 xml 文件属性相对应
public class Person {
    String id;
    String name;
    String age;
    String call;
    String language;
    public String getId() { return id; }
    public void setId(String id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getAge() { return age; }
    public void setAge(String age) { this.age = age; }
    public String getCall() { return call; }
    public void setCall(String call) { this.call = call; }
    public String getLanguage() { return language; }
    public void setLanguage(String language) { this.language = language; }
}
 

//2.新建 解析处理类SAXParseHandler 继承 默认处理类DefaultHandler
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.util.ArrayList;

public class SAXParseHandler extends DefaultHandler {
    Person person = null;
    String value = null;
    int personCount = 0;
    private ArrayList<Person> personList = new ArrayList<Person>();
    public ArrayList<Person> getPersonList() {
        return personList;
    }
    @Override
    public void startDocument() throws SAXException {
        System.out.println("===== SAX开始解析 ======");
        super.startDocument();
    }
    @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("persons")) {
            System.out.println("\t xml 文件开始遍历");
        } else if (qName.equals("person")) {
            System.out.println("\t\t ==========开始遍历人员信息=============");
            personCount++;
            person = new Person();

            int len = attributes.getLength();
            for(int i = 0; i < len; i++) {
                String name = attributes.getQName(i);
                String value = attributes.getValue(i);
                System.out.println("\t\t\t 属性名: " + name + "属性值: " + name);
                if(name.equals("id")) {
                    person.setId(value);
                }
            }
        } else {
            System.out.print("\t\t\t 节点名称: " + qName + "\t");
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        super.endElement(uri, localName, qName);
        if (qName.equals("persons")) {
            System.out.println("\t========== xml 文件遍历结束 ============");
        } else if (qName.equals("person")) {
            personList.add(person);
            person = null;
            System.out.println("\t\t ================== 人员信息遍历结束 =================");
        } else if(qName.equals("name")) {
            person.setName(value);
        } else if(qName.equals("age")) {
            person.setAge(value);
        } else if(qName.equals("call")) {
            person.setCall(value);
        } else if(qName.equals("language")) {
            person.setLanguage(value);
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        super.characters(ch, start, length);
        value = new String(ch, start, length);
        if(!value.trim().equals("")) {
            System.out.print("节点的值是: " + value);
            System.out.println();
        }
    }
}
 
3.测试
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.util.ArrayList;

public class SAXParseTest {
    public static void main(String[] args) {
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        try {
            SAXParser saxParser = saxParserFactory.newSAXParser();
            SAXParseHandler saxParseHandler = new SAXParseHandler();
            saxParser.parse("information.xml", saxParseHandler);

            ArrayList<Person> personList = saxParseHandler.getPersonList();
            System.out.println("共有" + personList.size() + "个人");
            for (Person person : personList) {
                System.out.print("id: " + person.getId() + "\t");
                System.out.print("age: " + person.getAge() + "\t");
                System.out.print("call: " + person.getCall() + "\t");
                System.out.print("language: " + person.getLanguage() + "\t");
                System.out.print("name: " + person.getName());
                System.out.println();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

3.JDOM解析(第三方提供)

1.下载 jdom.jar

2.新建person实体类

3.编写转换示例代码

import com.jack.psvm.sax.Person;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

public class jdomParseTest {
    private static ArrayList<Person> personList = new ArrayList();
    private static int personCount = 0;
    public static void main(String[] args) {
        SAXBuilder saxBuilder = new SAXBuilder();

        try {
            FileInputStream fileInputStream = new FileInputStream("information.xml");
            Document document = saxBuilder.build(fileInputStream);
            Element rootElement = document.getRootElement();
            List<Element> childrenList = rootElement.getChildren();
            System.out.println("============= 开始遍历人员信息 ============");
            for (Element child : childrenList) {
                ++personCount;
                System.out.println("\t ===== 第" + personCount + "一个人员信息开始遍历: ====");
                Person person = new Person();
                /* 属性值 */
                List<Attribute> attributes = child.getAttributes();
                System.out.print("\t\t 属性 --> ");
                for (Attribute attribute : attributes) {
                    String name = attribute.getName();
                    String value = attribute.getValue();
                    System.out.print( name + ": " + value + "\t");
                }
                System.out.println();
                /* 子节点信息 */
                List<Element> children = child.getChildren();
                System.out.print("\t\t 子节点 --> ");
                for (Element element : children) {
                    String name = element.getName();
                    String value = element.getValue();
                    System.out.print(name + ": " + value + "\t");
                    if(name.equals("name")) {
                        person.setName(value);
                    } else if(name.equals("age")) {
                        person.setAge(value);
                    } else if(name.equals("call")) {
                        person.setCall(value);
                    } else if(name.equals("language")) {
                        person.setLanguage(value);
                    }
                }
                System.out.println();
                System.out.println("\t ===== 第" + personCount + "个人员信息遍历结束: ====");
                personList.add(person);
                person = null;
            }
            System.out.println("============= 人员信息遍历结束 ============");
            System.out.println("所有人员信息集结: ");
            for (Person person : personList) {
                System.out.print("age: " + person.getAge() + "\t");
                System.out.print("call: " + person.getCall() + "\t");
                System.out.print("language: " + person.getLanguage() + "\t");
                System.out.print("name: " + person.getName());
                System.out.println();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

4.DOM4J解析(第三方提供)

1.下载 dom4j.jar

import com.jack.psvm.sax.Person;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class DOM4JParseTest {
    private static int personCount = 0;
    private static ArrayList<Person> personList = new ArrayList<Person>();
    public static void main(String[] args) {
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read("information.xml");
            Element persons = document.getRootElement();
            Iterator<Element> elementIterator = persons.elementIterator();
            System.out.println("=============== 开始遍历人员信息 =============");
            while (elementIterator.hasNext()) {
                Person personEntity = new Person();
                ++personCount;
                System.out.println("\t =====开始遍历第 " + personCount + " 个人员信息======");
                Element person = elementIterator.next();
                /* 获取属性值 */
                List<Attribute> attributes = person.attributes();
                System.out.print("\t\t 属性: ");
                for (Attribute attribute : attributes) {
                    System.out.print(attribute.getName() + ": " + attribute.getValue() + "\t");
                }
                /* 获取字节点的信息 */
                System.out.println();
                System.out.print("\t\t person 子节点: ");
                Iterator<Element> personElement = person.elementIterator();
                while (personElement.hasNext()) {
                    Element next = personElement.next();
                    String name = next.getName();
                    String value = next.getStringValue();
                    System.out.print(name + ": " + value + "\t");
                    if(name.equals("name")) {
                        personEntity.setName(value);
                    } else if(name.equals("age")) {
                        personEntity.setAge(value);
                    } else if(name.equals("call")) {
                        personEntity.setCall(value);
                    } else if(name.equals("language")) {
                        personEntity.setLanguage(value);
                    }
                }
                personList.add(personEntity);
                personEntity = null;
                System.out.println();
                System.out.println("\t =====第 " + personCount + " 个人员信息遍历结束======");
            }
            System.out.println("=============== 人员信息遍历结束 =============");
            System.out.println("============== 人员集结:  =============");
            for (Person person : personList) {
                System.out.print("name: " + person.getName());
                System.out.print("age: " + person.getAge() + "\t");
                System.out.print("call: " + person.getCall() + "\t");
                System.out.print("language: " + person.getLanguage() + "\t");
                System.out.println();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaMianJing/202306/16880928716939.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者