java基礎之XML

java基礎之XML

XML是一種通用的數據交換格式,它的平臺無關性、語言無關性、系統無關性、給數據集成與交互帶來了極大的方便。本篇文章重點介紹DOM4J對XML文件的一些操做。spring

1. XML解析概述

  常看法析方式和解析器dom

  1. DOM:要求解析器把整個XML文檔裝載到內存,並解析成一個Document對象。
    優勢:元素與元素之間保留結構關係,故能夠進行增刪改查操做。
    缺點:XML文檔過大,可能出現內存溢出顯現。
  2. SAX:是一種速度更快,更有效的方法。它逐行掃描文檔,一邊掃描一邊解析。並以事件驅動的方式進行具體解析,每執行一行,都將觸發對應的事件。
    優勢:處理速度快,能夠處理大文件
    缺點:只能讀,逐行後將釋放資源。

2. DOM4J介紹

2.1 經常使用包

包名 做用
import org.dom4j.Document; Document文檔類
import org.dom4j.Element 元素節點類
import org.dom4j.QName; 一個對元素名字的封裝類
import org.dom4j.io.SAXReader; sax讀取類
import org.dom4j.io.XMLWriter xml寫入類
import org.dom4j.io.OutputFormat 輸出格式

2.2 內置元素

元素 含義
Attribute 定義了 XML 的屬性。
Branch 指可以包含子節點的節點。如XML元素(Element)和文檔(Docuemnts)定義了一個公共的行爲
CDATA 定義了 XML CDATA 區域
CharacterData 是一個標識接口,標識基於字符的節點。如CDATA,Comment, Text.
Comment 定義了 XML 註釋的行爲
Document 定義了XML 文檔
DocumentType 定義 XML DOCTYPE 聲明
Element 定義XML 元素
ElementHandler 定義了Element 對象的處理器
ElementPath 被 ElementHandler 使用,用於取得當前正在處理的路徑層次信息
Entity 定義 XML entity
Node 爲dom4j中全部的XML節點定義了多態行爲
NodeFilter 定義了在dom4j 節點中產生的一個濾鏡或謂詞的行爲(predicate)
ProcessingInstruction 定義 XML 處理指令
Text 定義 XML 文本節點
Visitor 用於實現 Visitor模式
XPath 在分析一個字符串後會提供一個 XPath 表達式

2.2 Element類

方法 含義
getQName() 元素的QName對象
getNamespace() 元素所屬的Namespace對象
getNamespacePrefix() 元素所屬的Namespace對象的prefix
getNamespaceURI() 元素所屬的Namespace對象的URI
getName() 元素的local name
getQualifiedName() 元素的qualified name
getText() 元素所含有的text內容,若是內容爲空則返回一個空字符串而不是null
getTextTrim() 元素所含有的text內容,其中連續的空格被轉化爲單個空格,該方法不會返回null
attributeIterator() 元素屬性的iterator,其中每一個元素都是

2.3 Attribute類

方法 含義
attributeValue() 元素的某個指定屬性所含的值
elementIterator() 元素的子元素的iterator,其中每一個元素都是Element對象
element() 元素的某個指定(qualified name或者local name)的子元素
elementText() 元素的某個指定(qualified name或者local name)的子元素中的text信息
getParent() 元素的父元素
getPath() 元素的XPath表達式,其中父元素的qualified name和子元素的qualified name之間使用」/」分隔
isTextOnly() 是否該元素只含有text或是空元素
isRootElement() 是否該元素是XML樹的根節點

2.4 經常使用操做

  • 讀取xml文件,得到document對象.
SAXReader reader = new SAXReader();
Document  document = reader.read(new File("***.xml"));
  • 解析XML形式的文本,獲得document對象.
String text = "<members></members>";
Document document = DocumentHelper.parseText(text);
  • 獲取根節點
Element root = dom.getRootElement();
  • 取得某節點的單個子節點
Element memberElm=root.element("title");
  • 獲取節點文字
String text=memberElm.getText();
  • 取得某節點下名爲"title"全部字節點並進行遍歷
List list = rootElm.elements("member");
Iterator<Element> it = list.iterator(); 
while(it.hasNext()){
   Element elm = it.next();
   // do something...
}
  • 在某節點下添加子節點.
Element ageElm = newMemberElm.addElement("age");
  • 設置節點文字.
ageElm.setText("29");
  • 刪除某節點.
parentElm.remove(childElm);
  • 取得某節點下的某屬性
Element root=document.getRootElement();    
    Attribute attribute=root.attribute("id");
  • 設置某節點的屬性和文字.
newMemberElm.addAttribute("name", "sitinspring");
  • 設置屬性的文字
Attribute attribute=root.attribute("name");
attribute.setText("sitinspring");
  • 刪除某屬性
Attribute attribute=root.attribute("size");// 屬性名name
root.remove(attribute);

3. 代碼演示

3.1 DOM4J讀取xml文件

  test.xml函數

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
    <book id="1">
        <title>巴黎聖母院</title>
        <author>雨果</author>
    </book>
    <book id="2">
        <title>飄</title>
        <author>米切爾</author>
    </book>    
</bookstore>

  1. 使用List列表解析xml編碼

import java.io.File;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
  
public class XmlDemo {
    public static void main(String[] args) throws Exception {
        SAXReader reader = new SAXReader();
        File file = new File("test.xml");
        Document document = reader.read(file);
        Element root = document.getRootElement();
        List<Element> childElements = root.elements();
        for (Element child : childElements) {
            //已知屬性名狀況下
            System.out.println("--->id: " + child.attributeValue("id"));
            System.out.println("title:" + child.elementText("title"));
            System.out.println("author:" + child.elementText("author"));

            //未知屬性名狀況下
            /*List<Attribute> attributeList = child.attributes();
            for (Attribute attr : attributeList) {
                System.out.println(attr.getName() + ": " + attr.getValue());
            }
            List<Element> elementList = child.elements();
            for (Element ele : elementList) {
                System.out.println(ele.getName() + ": " + ele.getText());
            }
            System.out.println();*/
           
        }
    }
}
//輸出結果:
--->id: 1
title:巴黎聖母院
author:雨果
--->id: 2
title:飄
author:米切爾

  2. 使用Iterator解析xmlspa

public class XmlDemo {
    public static void main(String[] args) throws Exception {
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File("test.xml"));
        Element root = document.getRootElement();
          
        Iterator<Element> it = root.elementIterator();
        while (it.hasNext()) {
            Element element = it.next();
            
            //未知屬性名稱狀況下
            Iterator<Element> attrIt = element.attributeIterator();
            while (attrIt.hasNext()) {
                Attribute a  = (Attribute) attrIt.next();
                System.out.println(a.getValue());
            }
              
            Iterator<Element> eleIt = element.elementIterator();
            while (eleIt.hasNext()) {
                Element e =  eleIt.next();
                System.out.println(e.getName() + ": " + e.getText());
            }
            System.out.println();
              
            //已知元素名狀況下  
            /*System.out.println("id: " + element.attributeValue("id"));
            System.out.println("title: " + element.elementText("title"));
            System.out.println("author: " + element.elementText("author"));
            System.out.println();*/
        }
    }
}
//輸出結果:
id: 1
title:巴黎聖母院
author:雨果

id: 2
title:飄
author:米切爾

3.2 DOM4J建立xml文件

public class XmlDemo {
    public static void main(String[] args) throws Exception {
        Document doc = DocumentHelper.createDocument();
        //增長根節點
        Element books = doc.addElement("bookstore");
        //增長子元素
        Element book1 = books.addElement("book");
        Element title1 = book1.addElement("title");
        Element author1 = book1.addElement("author");
          
        Element book2 = books.addElement("book");
        Element title2 = book2.addElement("title");
        Element author2 = book2.addElement("author");
          
        //爲子節點添加屬性
        book1.addAttribute("id", "3");
        //爲元素添加內容
        title1.setText("戰爭與和平");
        author1.setText("列夫托爾斯泰");
          
        book2.addAttribute("id", "4");
        title2.setText("紅樓夢");
        author2.setText("曹雪芹");
          
        //實例化輸出格式對象
        OutputFormat format = OutputFormat.createPrettyPrint();
        //設置輸出編碼
        format.setEncoding("UTF-8");
        //建立須要寫入的File對象
        File file = new File("test2.xml");
        //生成XMLWriter對象,構造函數中的參數爲須要輸出的文件流和格式
        XMLWriter writer = new XMLWriter(new FileOutputStream(file), format);
        //開始寫入,write方法中包含上面建立的Document對象
        writer.write(doc);
    }
}

  運行結果(項目根目錄下):code

<?xml version="1.0" encoding="UTF-8"?>

<bookstore>
  <book id="3">
    <title>戰爭與和平</title>
    <author>列夫托爾斯泰</author>
  </book>
  <book id="4">
    <title>紅樓夢</title>
    <author>曹雪芹</author>
  </book>
</bookstore>

3.2 DOM4J修改xml文件

public class XmlDeml {
    public static void main(String[] args) throws Exception {
        SAXReader reader = new SAXReader();
        File file = new File("test.xml");
        Document document = reader.read(file);
        Element root = document.getRootElement();
        Element nameElement = root.element("book").element("author");
        nameElement.setText("魯迅");
        //寫回XML文檔
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(new FileOutputStream("test.xml"), format);
        writer.write(document);
        writer.close();
    }
}

  運行結果(項目根目錄下):orm

<?xml version="1.0" encoding="UTF-8"?>

<bookstore> 
  <book id="1"> 
    <title>巴黎聖母院</title>  
    <author>魯迅</author> 
  </book> 
</bookstore>
相關文章
相關標籤/搜索