• java读取XML文件的四种方法总结(必看篇)


    1.   https://www.jb51.net/article/115316.htm

    2. JAVA对XML文件的读写  https://www.cnblogs.com/cheng18/p/12052525.html

    3. Java操作XML的工具类  https://www.cnblogs.com/DreamDrive/p/5762605.html 

    4. Java用SAX解析XML   https://my.oschina.net/ydsakyclguozi/blog/493509

     

    <?xml version="1.0" encoding="UTF-8" ?>
    <!--
    <?xml version="1.0" encoding="UTF-8" ?>
    以上内容就是xml文件的声明,
    version="1.0" version表示xml的版本
    encoding="utf-8"   encoding表示xml文件本身的编码
    -->
    <books>
        <book sn="SN321324"><!-- book表示一个图书信息 sn属性表示图书序列号-->
            <name>时间简历</name><!--name标签表示书名 -->
            <author>陈彬
                <![CDATA[>>>><<<<<陈彬]]>
            </author><!--auther表示作者-->
            <price>23</price><!--price表示价格-->
        </book>
        <book sn="SN238238">
            <name>从Java入门到放弃</name>
            <author>康师傅</author>
            <price>22</price>
        </book>
    </books>
     

    JAVA操作XML文档主要有四种方式,分别是DOM、SAX、JDOM和DOM4J,DOM和SAX是官方提供的,而JDOM和DOM4J则是引用第三方库的,其中用的最多的是DOM4J方式。运行效率和内存使用方面最优的是SAX,但是由于SAX是基于事件的方式,所以SAX无法在编写XML的过程中对已编写内容进行修改,但对于不用进行频繁修改的需求,还是应该选择使用SAX。

    下面基于这四种方式来读取XML文件。

    第一,以DOM的方式实现。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    package xmls;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import java.io.File;
    import java.io.IOException;
    /**
     * Created by lenovo on 2017-6-3.
     */
    public class DOMReadDemo {
      public static void main(String[] args){
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try{
          DocumentBuilder db = dbf.newDocumentBuilder();
          Document document = db.parse("src/xmls/DOM.xml");
          NodeList booklist = document.getElementsByTagName("book");
          for(int i = 0; i < booklist.getLength(); i++){
            System.out.println("--------第" + (i+1) + "本书----------");
            Element ele = (Element) booklist.item(i);
            NodeList childNodes= ele.getChildNodes();
            for(int j = 0; j < childNodes.getLength(); j++){
              Node n = childNodes.item(j);
              if(n.getNodeName() != "#text"){
                System.out.println(n.getNodeName() + ":" + n.getTextContent());
              }
            }
            System.out.println("---------------------------------");
          }
        }catch (ParserConfigurationException e){
          e.printStackTrace();
        }catch (IOException e){
          e.printStackTrace();
        }catch (SAXException e){
          e.printStackTrace();
        }
      }
    }

    第二,以SAX的方式实现。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    package xmls;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    /**
     * Created by lenovo on 2017-6-1.
     */
    public class xmlTest2 {
      public static void main(String[] args){
        SAXParserFactory spf = SAXParserFactory.newInstance();
        try{
          SAXParser sp = spf.newSAXParser();
          SAXParserHandler handler = new SAXParserHandler();
          sp.parse("src\\xmls\\book.xml", handler);
        }catch (Exception e){
          e.printStackTrace();
        }
      }
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    package xmls;
    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;
    /**
     * Created by lenovo on 2017-6-1.
     */
    public class SAXParserHandler extends DefaultHandler {
      @Override
      public void startDocument() throws SAXException {
        super.startDocument();
        System.out.println("SAX解析开始");
      }
      @Override
      public void endDocument() throws SAXException {
        super.endDocument();
        System.out.println("SAX解析结束");
      }
      @Override
      public void startElement(String s, String s1, String s2, Attributes attributes) throws SAXException {
        super.startElement(s, s1, s2, attributes);
        System.out.println(s2);
        for(int i = 0; i < attributes.getLength(); i++){
          String name = attributes.getQName(i);
          String value = attributes.getValue(name);
          System.out.println("属性值:" + name + "=" + value);
        }
      }
      @Override
      public void endElement(String s, String s1, String s2) throws SAXException {
        super.endElement(s, s1, s2);
        if(s2.equals("book")){
          System.out.println("-----------------------");
        }
      }
      @Override
      public void characters(char[] ch, int start, int length) throws SAXException {
        super.characters(ch, start, length);
        String value = new String(ch, start, length);
        if(value.trim().equals("")){
          return;
        }
        System.out.println(value);
      }
    }

    第三,以JDOM的方式实现。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    package xmls;
    import org.jdom2.Attribute;
    import org.jdom2.Document;
    import org.jdom2.Element;
    import org.jdom2.JDOMException;
    import org.jdom2.input.JDOMParseException;
    import org.jdom2.input.SAXBuilder;
    import java.io.*;
    import java.util.List;
    /**
     * Created by lenovo on 2017-6-2.
     */
    public class JDOMTest {
      public static void main(String[] args){
        SAXBuilder saxBuilder = new SAXBuilder();
        InputStream in;
        try{
          in = new FileInputStream(new File("src\\xmls\\book.xml"));
          Document document = saxBuilder.build(in);
          Element rootElement = document.getRootElement();
          List<Element> bookList = rootElement.getChildren();
          for(Element book: bookList){
            System.out.println("第" + (bookList.indexOf(book)+1) + "本书!");
            List<Attribute> attrs = book.getAttributes();
            for(Attribute attr: attrs){
              System.out.println(attr.getName() + "=" + attr.getValue());
            }
            for(Element item: book.getChildren()){
              System.out.println(item.getName() + ":" + item.getValue());
            }
            System.out.println("------------------------------------");
          }
        }catch (FileNotFoundException e){
          e.printStackTrace();
        }catch (JDOMException e){
          e.printStackTrace();
        }catch (IOException e){
          e.printStackTrace();
        }
      }
    }

    第四,以DOM4J的方式实现。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    package xmls;
    import org.dom4j.*;
    import org.dom4j.io.OutputFormat;
    import org.dom4j.io.SAXReader;
    import org.dom4j.io.XMLWriter;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.Iterator;
    import java.util.List;
    /**
     * Created by lenovo on 2017-6-2.
     */
    public class DOM4JTest {
      public void parseXML(){
        SAXReader saxReader = new SAXReader();
        try{
          Document document = saxReader.read(new File("src\\xmls\\book.xml"));
          Element rootElement = document.getRootElement();
          Iterator it = rootElement.elementIterator();
          while (it.hasNext()){
            Element book = (Element)it.next();
            List<Attribute> attrs = book.attributes();
            for(Attribute attr: attrs){
              System.out.println("属性名:" + attr.getName() + "---- 属性值:" + attr.getValue() );
            }
            Iterator cit = book.elementIterator();
            while (cit.hasNext()){
              Element child = (Element) cit.next();
              System.out.println("子节点:" + child.getName());
            }
          }
        }catch (DocumentException e){
          e.printStackTrace();
        }
      }
      public static void main(String[] args){
        DOM4JTest dom4JTest = new DOM4JTest();
        dom4JTest.parseXML();
      }
    }

    以上这篇java读取XML文件的四种方法总结(必看篇)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

  • 相关阅读:
    Haskell Types与Typeclasses
    Haskell Tuple相关总结
    Haskell List相关操作
    Emacs 常用快捷键
    Emacs 参考资料
    Haskell Platform (windows)
    生成zip压缩包
    递归复制一个文件
    写表格
    读表格
  • 原文地址:https://www.cnblogs.com/kelelipeng/p/15711622.html
Copyright © 2020-2023  润新知