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>

 

 

XML解析方式

SAX解析方式

SAX(simple API for XML)是一種XML解析的替代方法。相比於DOM,SAX是一種速度更快,更有效的方法。它逐行掃描文檔,一邊掃描一邊解析。而且相比於DOM,SAX可以在解析文檔的任意時刻停止解析。 其優缺點分別為:
優點: 解析可以立即開始,速度快,沒有內存壓力
缺點: 不能對節點做修改

DOM解析方式

DOM:(Document Object Model, 即文檔對象模型) 是 W3C 組織推薦的處理 XML 的一種方式。DOM解析器在解析XML文檔時,會把文檔中
的所有元素,按照其出現的層次關系,解析成一個個Node對象(節點)。其優缺點分別為:
優點:把xml文件在內存中構造樹形結構,可以遍歷和修改節點
缺點: 如果文件比較大,內存有壓力,解析的時間會比較長

JDOM和DOM4J解析方式

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);
   }
}

 

Java 解析xml中參數解釋-localName和qName

https://blog.csdn.net/django100/article/details/12707317

訂閱專欄 1. xml中的localName和QName <?xml version="1.0" encoding="utf-8"?> <websites xmlns:sina="http://www.sina.com" xmlns:baidu="http://www.baidu.com"> <sina:website sina:blog="blog.sina.com">新浪</sina:website> <baidu:website baidu:blog="hi.baidu.com">百度</baidu:website> </websites> Namespace(空間名稱,命名空間) 引入的原因是為了避免混淆。例如上面的這個XML文檔,sina和baidu都有blog屬性,定義了兩個namespace,就像sax官網說的,用namespace是為了實現更多的擴展功能,作為基本應用,很多時候都用不到它: sina的namespace: http://www.sina.com baidu的namespace:http://www.baidu.com xmlns:sina="http://www.sina.com" xmlns:baidu="http://www.baidu.com"> namespace的值可以任意,但是注意不要重復。一般默認的格式都是以url來作為namespace,比如 xmlns:android="http://schemas.android.com/apk/res/android。 Prefix(前綴) sina:blog中 sina 就是前綴。 LocalName(本地名稱) sina:blog 中 blog就是localName。 QName(Qualified Name) sina:blog就是QName,相當於前綴+":"+LocalName。 uri(不是url哈) 例如sina:blog的uri就是前綴sina的namespace,即"http://www.sina.com"。 2.sax解析localName與qName sax simple API for XML,現在有兩個版本,sax和sax2。 sax不支持LocalName、QName和uri。對於屬性sina:blog="blog.sina.com",sax解析的結果是LocalName=QName="sina:blog",uri="",value="blog.sina.com"。 sax2支持LocalName、QName、uri。對於屬性sina:blog="blog.sina.com",sax2解析的結果是LocalName="blog",QName="sina:blog",uri="",value="blog.sina.com"。
_______________________________________________________________________________________________________________________________________________________________________ 測試: TestSax.java package com.siqi.xml; import java.io.File; import java.io.FileReader; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; public class TestSax { public static void main(String... args) { try { //Sax2解析XML文檔 System.out.println("parse xml file use sax2"); SaxParseHandler sax2Handler = new SaxParseHandler(); XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setContentHandler(sax2Handler); xmlReader.setErrorHandler(sax2Handler); FileReader fileReader = new FileReader("./src/sample.xml"); xmlReader.parse(new InputSource(fileReader)); //sax1解析XML文檔 System.out.println("parse xml file use sax"); SaxParseHandler saxHandler = new SaxParseHandler(); SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); File file = new File("./src/sample.xml"); parser.parse(file, saxHandler); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

__________________________________________________________________________________________________________________________________________________________________________
SaxParseHandler.java package com.siqi.xml; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * 要用sax解析,需要實現一個ParseHandler * @author siqi * */ public class SaxParseHandler extends DefaultHandler{ /** * 重寫了DefaultHandler中的startElement函數,每解析到 * 一個元素(element)的時候都會觸發這個函數,並且將這個element * 的屬性attributes和值value當作參數傳進來。除了startElement, * 還有startDocument,endDOucment,endElement,要根據需要 * 重寫這些函數。 */ @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { //打印element的基本信息,qName System.out.println("Element qName : "+qName); System.out.println("Element localName: "+localName); System.out.println("Element uri : "+uri); //打印element的所有屬性attributes for(int i=0; i<attributes.getLength(); i++) { System.out.println(""); System.out.println(" attribute qName : "+attributes.getQName(i)); System.out.println(" attribute localName: "+attributes.getLocalName(i)); System.out.println(" attribute value : "+attributes.getValue(i)); System.out.println(" attribute uri : "+attributes.getURI(i)); } System.out.println(""); super.startElement(uri, localName, qName, attributes); } } sample.xml的內容最上面那個xml 執行結果: parse xml file use sax2 Element qName : websites Element localName: websites Element uri : Element qName : sina:website Element localName: website Element uri : http://www.sina.com attribute qName : sina:blog attribute localName: blog attribute value : blog.sina.com attribute uri : http://www.sina.com Element qName : baidu:website Element localName: website Element uri : http://www.baidu.com attribute qName : baidu:blog attribute localName: blog attribute value : hi.baidu.com attribute uri : http://www.baidu.com parse xml file use sax Element qName : websites Element localName: Element uri : attribute qName : xmlns:sina attribute localName: xmlns:sina attribute value : http://www.sina.com attribute uri : attribute qName : xmlns:baidu attribute localName: xmlns:baidu attribute value : http://www.baidu.com attribute uri : Element qName : sina:website Element localName: Element uri : attribute qName : sina:blog attribute localName: sina:blog attribute value : blog.sina.com attribute uri : Element qName : baidu:website Element localName: Element uri : attribute qName : baidu:blog attribute localName: baidu:blog attribute value : hi.baidu.com attribute uri : 對於sax2,正確的解析出了qName,LocalName和uri。sax不能識別出前綴和uri,qName=localName。

  

 

 

第三,以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文件的四種方法總結(必看篇)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM