java xml analytical methods (DOM, SAX, JDOM, DOM4J)

XML value Extensible Markup Language, is used to transmit and store data.

XMl particular:

  1. XMl document must contain a root element . The element is the parent of all other elements. XML document elements form a document tree, the tree of child elements of each element may be present.
  2. All XML elements must have a closing tag.
  3. XML tags are case sensitive, and all the property value date are required to be quoted.

XML elements:

XMl element only from beginning to end of the tag label part of the elements may include other elements, text, or both contain, can have attributes.

 

XML parsing

Based approach: the DOM , SAX

DOM parsing: platform-independent official analytical methods

SAX parsing: the Java in analytical methods based on event-driven

Extension method: JDOM , DOM4J ( on the basis of the method extend only Java analytical methods can be used )

 

1.DOM resolve

    advantage:

      · Form a tree structure, intuitively easy to understand

      · Parsing tree structure easy to modify retained in memory

    Disadvantages:

      • When xml the files are large, memory consumption is relatively large, easily affect the analytical performance and cause memory overflow

import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.util.LinkedList;
import java.util.List;

/**
 * DOM 解析xml
 */
public class DOM {
    public static void main(String[] args) throws Exception {
        // 1.创建 DocumentBuilderFactory 对象
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        // 2.通过 DocumentBuilderFactory对象创建 DocumentBuilder对象
        DocumentBuilder db =dbf.newDocumentBuilder ();
         // 3. Use DocumentBuilder object to load XML 
        the Document Document db.parse = ( "bean.xml" ); 
        System.out.println ( "------------- ----------------- ---- DOM start parsing xml " );
         // get xml files root 
        Element Element = Document.getDocumentElement (); 
        getNoeMsg (Element); 
        System.out.println ( "\ the n-\ the n------------------ end of the DOM parsing xml -----------------" ); 
    } 

    / ** 
     * Get the node information node 
     * @param node
      * / 
    public  static  void getNoeMsg (node node) {
         IF(node.getNodeType() == Node.ELEMENT_NODE){
            System.out.print("<" + node.getNodeName());
            getNodeAttrs(node);
            System.out.print(">\n");
            NodeList nodeList = node.getChildNodes();
            // 筛选出节点类型为ELEMENT_NODE 的节点
            List<Node> list = getNodeList(nodeList);
            Node childNode;
            int len = list.size();
            if(len == 0){
                System.out.print(node.getTextContent() + "\n");
            }else {
                for (int i = 0; i < len; i++){
                    if(list.get(i).getNodeType() == Node.ELEMENT_NODE){
                        childNode = list.get(i);
                        getNoeMsg(childNode);
                    }
                }
            }
            System.out.println("</" + node.getNodeName() + ">");
        }
    }

    /**
     * 获取Node节点的属性信息
     * @param node
     */
    public static void getNodeAttrs(Node node){
        NamedNodeMap attrs = node.getAttributes();
        Node attr;
        if(attrs.getLength() != 0){
            for (int i = 0, len = attrs.getLength(); i < len; i++){
                attr = attrs.item(i);
                System.out.print(" " + attr.getNodeName() + "='");
                System.out.print(attr.getNodeValue() + "'");
            }
        }
    }

    /**
     * 筛选出节点类型为ELEMENT_NODE 的节点
     * @param nodeList
     * @return
     */
    public static List<Node> getNodeList(NodeList nodeList){
        List<Node> list = new LinkedList<>();
        for (int i = 0,len = nodeList.getLength(); i < len; i++){
            if(nodeList.item(i).getNodeType() == Node.ELEMENT_NODE){
                list.add(nodeList.item(i));
            }
        }
        return list;
    }
}

 

2.SAX resolve

    advantage:

      · Event-driven model, memory consumption is relatively small

      · Only suitable for processing xml time data

    Disadvantages:

      · Easy coding

      · Difficult to simultaneously access the same xml many different data

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

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

public class SAX {
    public static void main(String[] args) throws Exception {
        // 1.创建SAXParserFactory对象
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        // 2.通过SAXParserFactory对象创建 SAXParser
        SAXParser saxParser = saxParserFactory.newSAXParser();
        //3. SAXParser loading parsed xml, and the type of incoming object DefaultHandler 
        saxParser.parse ( "bean.xml", new new SAXParserHandler ()); 
    } 

    static  class SAXParserHandler the extends DefaultHandler {
         / ** 
         * Analytical Method xml begin 
         * @ throws a SAXException
          * / 
        @Override 
        public  void the startDocument () throws a SAXException {
             Super .startDocument (); 
            of System.out.print ( "============= start parsing the SAX xml ====== ======= \ n-" ); 
        } 

        / ** 
         * analytical method ends execution xml
         * @Throws a SAXException
          * / 
        @Override 
        public  void the endDocument () throws a SAXException {
             Super .endDocument (); 
            of System.out.print ( "\ n-parsed xml == end of the SAX ============= =========== " ); 
        } 

        / ** 
         * analytical methods begin node 
         * @param URI 
         * @param the localName 
         * @param the qName 
         * @param Attributes 
         * @throws a SAXException
          * / 
        @Override 
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            super.startElement(uri, localName, qName, attributes);
            System.out.print("<" + qName);
            for (int i = 0,len = attributes.getLength(); i < len; i++){
                System.out.print(" " + attributes.getQName(i) + "='");
                System.out.print(attributes.getValue(i) + "'");
            }
            System.out.print(">");

        
         * Analytical method ends execution node/ **
        }
         * @param uri
         * @param localName
         * @param qName
         * @throws SAXException
         */
        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {
            super.endElement(uri, localName, qName);
            System.out.print("</" + qName + ">");
        }

        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            super.characters(ch, start, length);
            String str = new String(ch, start, length);
            System.out.print(str);
        }
    }
}

3.JDOM resolve

    feature:

      • Use a concrete class, do not use interface.

      · API extensive use of Collections class, open source

import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * <!--  引入JDOM依赖包 -->
 * <dependency>
 *     <groupId>org.jdom</groupId>
 *     <artifactId>jdom</artifactId>
 *     <version>1.1</version>
 * </dependency>
 */
public class{JDOM
     public  static  void main (String [] args) throws IOException, JDOMException {
         // 1. Create SAXBuilder objects 
        SAXBuilder SAXBuilder = new new SAXBuilder ();
         // 2. xml file input stream obtaining 
        the InputStream in = new new the FileInputStream ( "the bean. xml " );
         // 3. the method SAXBuilder through the build object to add to the xml file input stream object SAXBuilder 
        the document document = saxBuilder.build (in);
         // 4. root xml Get 
        the Element the rootElement = document.getRootElement ( );
         // The parsed xml root
        printNodeMsg(rootElement);
    }

    public static void printNodeMsg(Element element){
        System.out.print("<" + element.getName());
        // 获取节点的属性
        printAttrmsg(element);
        System.out.print(">\n");
        List<Element> elements = element.getChildren();
        for (Element e : elements){
            if(e.getChildren().size() > 0){
                printNodeMsg(e);
            }else {
                System.out.print("<" + e.getName());
                printAttrmsg(e);
                System.out.print(">");
                System.out.print(e.getValue());
                System.out.print("</" + e.getName() + ">\n");
            }
        }
        System.out.print("</" + element.getName() + ">\n");
    }

    /**
     * 获取节点的属性
     * @param element
     */
    public static void printAttrmsg(Element element){
        List<Attribute> attributes = element.getAttributes();
        for (Attribute attribute : attributes){
            System.out.print(" " + attribute.getName() + "='" + attribute.getValue() + "'");
        }
    }
}

4.DOM4J resolve

    feature:

    Use of interfaces and abstract base class methods

    * Has excellent performance, good flexibility, powerful and extremely easy to use.

    · Open Source

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Iterator;

/**
 * <!-- dom4j依赖包 -->
 * <dependency>
 *     <groupId>dom4j</groupId>
 *     <artifactId>dom4j</artifactId>
 *     <version>1.6.1</version>
 * </dependency>
 */
public class DOM4J {
    public static voidmain (String [] args) throws a FileNotFoundException, DocumentException {
         // 1. Create an object SAXReader 
        SAXReader SAXReader = new new SAXReader ();
         // 2. SAXReader object by the read method, the input stream xml loading 
        the Document Document saxReader.read = ( new new the FileInputStream ( "bean.xml" ));
         // 3. by obtaining the root xml Document object 
        the Element the rootElement = document.getRootElement ();
         // 4. by parsing the root xml 
        printNodeMsg (the rootElement); 
    } 

    public  static  void printNodeMsg (the Element Element) { 
        of System.out.print ("<" + element.getName());
        // 获取节点的属性
        printAttrmsg(element);
        System.out.print(">\n");
        Iterator<Element> elementIterator = element.elementIterator();
        Element e;
        while (elementIterator.hasNext()){
            e = elementIterator.next();
            if(e.elementIterator().hasNext()){
                printNodeMsg(e);
            }else {
                System.out.print("<" + e.getName());
                printAttrmsg(e);
                System.out.print(">");
                System.out.print(e.getStringValue());
                System.out.print("</" + e.getName() + ">\n");
            }
        }
        System.out.print("</" + element.getName() + ">\n");
    }

    /**
     * 获取节点的属性
     * @param element
     */
    public static void printAttrmsg(Element element){
        Iterator<Attribute> attributeIterator = element.attributeIterator();
        Attribute attribute;
        while (attributeIterator.hasNext()){
            attribute = attributeIterator.next();
            System.out.print(" " + attribute.getName() + "='" + attribute.getValue() + "'");
        }
    }
}

 

 

Guess you like

Origin www.cnblogs.com/www-123456/p/11110721.html