schema文件及XML文件的DOM和Sax解析

schema文件

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
        targetNamespace="http://www.example.org/book"
        xmlns:book="http://www.example.org/book"
        elementFormDefault="qualified">
        <!--创建books根元素-->
        <element name="books">
            <complexType>
                <sequence>
                    <element name="book" maxOccurs="unbounded" minOccurs="1">
                        <complexType>
                            <sequence>
                                <element name="name" type="string"/>
                                <element name="author" type="string" maxOccurs="2"/>
                                <element name="price" type="decimal"/>
                                <element name="date" type="date"/>
                                <element name="pageNumbers" type="int" minOccurs="0" maxOccurs="2"/>
                            </sequence>
                            <attribute name="id" type="ID" use="required"/>
                            <attribute name="name" type="string"/>
                        </complexType>
                    </element>
                </sequence>
            </complexType>
        </element>
</schema>
<?xml version="1.0" encoding="UTF-8"?>
<books xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.example.org/book"
       xmlns:book="http://www.example.org/book"
       xsi:schemaLocation="http://www.example.org/book book.xsd">
    <book:book id="CSN001" name="图书1">
        <book:name></book:name>
        <book:author>图书作者1</book:author>
        <book:author>图书作者</book:author>
        <book:price>66.6</book:price>
        <book:date>1966-10-22</book:date>
        <book:pageNumbers>1</book:pageNumbers>
    </book:book>
</books>

xml解析

<?xml version="1.0" encoding="UTF-8"?>
<dataSources>
    <!-- 定义MySQL数据源 -->
    <dataSource id="mysql" class="xxx.xxx.xx">
        <property name="driverClassName">com.mysql.jdbc.Driver</property>
        <property name="url">jdbc:mysql://127.0.0.1:3306/userdb</property>
        <property name="username">root</property>
        <property name="password">123</property>
    </dataSource>
    
    <!-- 定义Oracle的数据源 -->
    <dataSource id="oracle" class="xxx.xxx.xx">
        <property name="driverClassName">com.oracle.jdbc.OracleDriver</property>
        <property name="url">jdbc:oracle:thin:@127.0.0.1:1521:ORCL</property>
        <property name="username">scott</property>
        <property name="password">tiger</property>
    </dataSource>
</dataSources>
package com.demo.dom;

import java.io.InputStream;

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

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 使用DOM解析XML文件
 * 
 * 把XML文件转换后为流程在把流在内存中构建一个DOM模型,使用对应API操作DOM树
 * 
 * @author Administrator
 *
 */
public class DOMParser {

    public static void main(String[] args) {
        long start = System.nanoTime();
        try {
            // 创建一个文档构建工厂对象
            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
            // 通过工厂对象创建一个文档构建对象
            DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
            // 吧XML转换为输入流操作
            InputStream inputStream = DOMParser.class.getClassLoader().getResourceAsStream("datasource.xml");
            // 通过文档构建对象构建一个文档对象
            Document document = documentBuilder.parse(inputStream);
            // 获取文档中的根元素
            Element rootElement = document.getDocumentElement();
            // 获取根元素先所有dataSource子节点
            NodeList nodeList = rootElement.getChildNodes();

            for (int i = 0; i < nodeList.getLength(); i++) {
                /**
                 * 3: 换行节点->文本节点 8: 注释节点 1: 元素节点
                 */
                Node node = nodeList.item(i);
                // 判断元素节点才操作
                if (Node.ELEMENT_NODE == node.getNodeType()) {
                    // 读取属性节点的值
                    String clazz = node.getAttributes().getNamedItem("class").getNodeValue();
                    String id = node.getAttributes().getNamedItem("id").getNodeValue();
                    System.out.println("class="+clazz);
                    System.out.println("id="+id);
                    // 获取元子节点
                    NodeList datasourceNodes = node.getChildNodes();
                    for (int j = 0; j < datasourceNodes.getLength(); j++) {
                        Node dataSourceNode = datasourceNodes.item(j);
                        
                        if (Node.ELEMENT_NODE == dataSourceNode.getNodeType()) {
                            // 获取属性的值
                            String nameValue = dataSourceNode.getAttributes().getNamedItem("name").getNodeValue();
                            String contentValue = dataSourceNode.getTextContent();
                            System.out.println(nameValue+"="+contentValue);
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        
        long end = System.nanoTime();
        System.out.println(end - start);
    }
    
    
    

}
package com.demo.sax;

import java.io.InputStream;

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;

import com.demo.dom.DOMParser;

/**
 * Sax解析
 * 
 * @author Administrator
 *
 */
public class SaxParserDemo {
    public static void main(String[] args) {
        long start = System.nanoTime();
        // 创建一个Sax工厂对象->工厂设计
        SAXParserFactory factory = SAXParserFactory.newInstance();
        try {
            // 创建解析器
            SAXParser saxParser = factory.newSAXParser();
            // 吧XML转换为输入流操作
            InputStream inputStream = DOMParser.class.getClassLoader().getResourceAsStream("datasource.xml");
            saxParser.parse(inputStream, new DefaultHandler() {
                //解析开始标题文档
                public void startDocument() throws SAXException {
                    System.out.println("<?xml version= 1.0 encoding= utf-8 ?>");
                }
                //解析节点
                @Override
                public void startElement(String uri, String localName,
                        String qName, Attributes attributes) throws SAXException {
                    System.out.print("<"+qName+" ");
                    for (int i = 0; i < attributes.getLength(); i++) {
                        System.out.print(attributes.getQName(i)+"="+attributes.getValue(i)+" ");
                    }
                    System.out.print(">");
                }
           
                @Override
                //解析结束
                public void endElement(String uri, String localName, String qName)
                        throws SAXException {
                    System.out.print("</"+qName+">");
                }
     
                @Override
                //解析内容
                public void characters(char[] ch, int start, int length)
                        throws SAXException {
                    String string = new String(ch, start, length);
                    System.out.print(string);
                }

            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        long end = System.nanoTime();
        System.out.println(end - start);
    }
    
    /**
     * 定义默认处理的内部类
     * @author Administrator
     *
     */
    private static class XMLHanlder extends DefaultHandler {

        @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);
            System.out.println(attributes.getValue("id"));
            System.out.println(attributes.getValue("class"));
        }

        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {
            System.out.println("解析结束");
        }

        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            System.out.println("解析内容");
            System.out.println(new String(ch,start, length));
        }
        
    }
}
原文地址:https://www.cnblogs.com/sunBinary/p/10618109.html