码迷,mamicode.com
首页 > 编程语言 > 详细

Java 操作XML (org.xml.sax)

时间:2020-04-07 15:39:51      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:throws   handler   cte   OLE   def   qname   一个   zha   add   

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)

标签:throws   handler   cte   OLE   def   qname   一个   zha   add   

原文地址:https://www.cnblogs.com/sweetXiaoma/p/12653588.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!