Java 操作XML (org.xml.sax)

Posted Sweet小马

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java 操作XML (org.xml.sax)相关的知识,希望对你有一定的参考价值。

package hello;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

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

public class XML_SAXReader {
    public static void main(String[] args) {
        try {
            XMLReader parser = XMLReaderFactory.createXMLReader();
            UserHandler userHandler = new UserHandler();
            parser.setContentHandler(userHandler);
            parser.parse("users.xml");
            System.out.println(userHandler.getNameList());

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    static class UserHandler extends DefaultHandler {
        private List<String> nameList;
        private boolean isName = false;

        public List<String> getNameList() {
            return nameList;
        }

        public void startDocument() throws SAXException {
            System.out.println("开始解析文档...");
            this.nameList = new ArrayList<String>();
        }

        // xml 文档解析结束
        public void endDocument() throws SAXException {
            System.out.println("...文档解析完毕");
        }

        // 访问某一个元素
        public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
            System.out.println("开始读取标签 " + qName);
            if (qName.equals("name")) {
                isName = true;
            }
        }

        // 结束访问元素
        public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
            System.out.println("结束读取标签 " + qName);
            if (isName) {
                isName = false;
            }
        }

        // 访问元素正文
        public void characters(char[] ch, int start, int length) {
            if (isName) {
                String name = new String(ch, start, length);
                System.out.println("userName: " + name);
                nameList.add(name);
            }
        }

    }
}
<?xml version="1.0" encoding="UTF-8"?>
<users>
    <user id="001">
        <name>Mary</name>
        <age>3</age>
        <sex>Female</sex>
    </user>
    <user id="002">
        <name>Mike</name>
        <age>18</age>
        <sex>Male</sex>
    </user>
    <user id="003">
        <name>ZhaZhaHui</name>
        <age>38</age>
        <sex>Male</sex>
    </user>
</users>

以上是关于Java 操作XML (org.xml.sax)的主要内容,如果未能解决你的问题,请参考以下文章

org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; java sax解析xml文档遇到的问题

SAX - DefaultHandler

org.xml.sax.SAXParseException:prolog 中不允许内容

XML编程总结——使用SAX接口操作xml

使用 SAX 读取 XML,跳过传递 org.xml.sax.SAXParseException 的节点

org.xml.sax.SAXParseException:处理指令不能以 xml 开头