zoukankan      html  css  js  c++  java
  • sax方式解析XML学习笔记

    原理:对文档进行顺序扫描,当扫描到文档(document)开始与结束,元素开始与结束、文档结束等地方

    通知事件处理函数,由事件处理函数相应动作然后继续同样的扫描,直至文档结束。

    优点:消耗资源比较少;适合大文件解析;

    缺点:只能读取不能修改;开发复杂。

    实例:

      xml

      

    <?xml version="1.0" encoding="UTF-8"?>
    <students>
    <student>
    <name id="001" xx="haha">张三</name>
    <sex>男</sex>
    <age>20</age>
    </student>
    <student>
    <name id="002" xx="哈哈">李四</name>
    <sex>女</sex>
    <age>18</age>
    </student>
    </students>

    //

    package com.java1234.xml;

    import java.io.IOException;

    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;

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

    public class sax01 extends DefaultHandler{

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
    System.out.println("扫描节点开始"+new String(ch,start,length));
    }

    @Override
    public void endDocument() throws SAXException {
    System.out.println("扫描文档结束");
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
    System.out.println("扫描元素结束" + qName);
    }

    @Override
    public void startDocument() throws SAXException {
    System.out.println("扫描文档开始");
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
    System.out.println("扫描元素开始"+qName);
    if(attributes!=null){
    for(int i=0;i<attributes.getLength();i++){
    System.out.println(attributes.getQName(i)+":"+attributes.getValue(i));
    }
    }
    }

    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
    SAXParserFactory factory =SAXParserFactory.newInstance();
    SAXParser parser= factory.newSAXParser();
    parser.parse("src/NewFile.xml",new sax01());

    }

    }

  • 相关阅读:
    sql 四大排名函数--简介
    Markdown语法规则
    利用ADO操作外部数据——Excel之VBA(15)
    VBA中的用户信息交换——Excel之VBA(14)
    窗体和控件(2)——Excel之VBA(13)
    窗体和控件(1)——Excel之VBA(12)
    使用VBA数组公式——Excel之VBA(11)
    使用DIR函数合并多个文件的数据——Excel之VBA(10)
    ubuntu jupter python虚拟环境
    Pytorch_加载自己的数据集并训练
  • 原文地址:https://www.cnblogs.com/lmq3321/p/6672675.html
Copyright © 2011-2022 走看看