[Java拾遺一] XML的書寫規范與解析.


前言
今天天氣大好, 起了個大早開始總結一些常用的基礎知識.
XML一直來說都很陌生, 使用大多是用於配置文件, 之前並沒有細究過其中的約束規范, 今天剛好沒事來學習並總結下. 


1,XML基礎介紹
  XML 指可擴展標記語言(EXtensible Markup Language),也是一種標記語言,很類似 HTML.它的設計宗旨是傳輸數據,而非顯示數據它;標簽沒有被預定義,需要自行定義標簽。
  xml的作用:
    XML 是各種應用程序之間進行數據傳輸的最常用的工具,並且在信息存儲和描述領域變得越來越流行。簡單的說,我們在開發中使用XML主要有以下兩方面應用.
           a.XML做為數據交換的載體,用於數據的存儲與傳輸
    b.XML做為配置文件
2,書寫規范

注意事項:
    xml必須有根元素
(只有一個)

xml標簽必須有關閉標簽

xml標簽對大小寫敏感

xml的屬性值須加引號

特殊字符必須轉義

xml中的標簽名不能有空格

空格/回車/制表符在xml中都是文本節點

xml必須正確地嵌套

    我們將符合上述書寫規則的XML叫做格式良好的XML文檔。

在講述XML組成部分前,我們必須對XML的樹型結構有所了解.下面是一個簡單的XML

<bookstore>
<book category="COOKING">
  <title lang="en">Everyday Italian</title> 
  <author>Giada De Laurentiis</author> 
  <year>2005</year> 
  <price>30.00</price> 
</book>
<book category="CHILDREN">
  <title lang="en">Harry Potter</title> 
  <author>J K. Rowling</author> 
  <year>2005</year> 
  <price>29.99</price> 
</book>
<book category="WEB">
  <title lang="en">Learning XML</title> 
  <author>Erik T. Ray</author> 
  <year>2003</year> 
  <price>39.95</price> 
</book>
</bookstore>

圖片1

對於一個xml文件,首先必須要有根元素,該元素是所有其它元素的父元素。而在xml中所有元素形成了一棵樹。父,子及同胞等術語描述了元素之間的關系。所有的元素都可以擁有子元素。相同層級上的子元素成為同胞。
所有元素都可以擁有文本內容和屬性。
    Root  根元素
    Element 元素
    Attribute 屬性
    Text  文本
在開發中,我們將上述內容也統稱為Node(節點)。

3,xml的作用詳解 
    1.不同語言之間交換數據-- 用數據庫代替

    2.配置文件-- ☆

xml的約束:
        作用:明確的告訴我們那些元素和屬性可以寫,以及他們的順序如何.
        分類:DTD約束和SCHEMA約束
        要求:給你xml約束你可以寫出對應的xml文檔即可.
        1, DTD約束:struts hibernate中有使用
            與xml文檔的關聯:
                方式1:內部關聯
                    格式:<!DOCTYPE 根元素名稱 [dtd的語法]>

                方式2:外部關聯--系統關聯
                    格式:<!DOCTYPE 根元素名稱 SYSTEM  "dtd路徑">
                    dtd的后綴名是 .dtd
                方式3:外部關聯--公共關聯
                    格式:<!DOCTYPE 根元素名稱 PUBLIC "dtd的名稱" "dtd路徑">
               
            元素:
                格式1:<!ELEMENT 元素的名稱 (內容)>
                格式2:<!ELEMENT 元素的名稱 類別>
            屬性:
                格式:<!ATTLIST 元素的名稱 屬性的名稱 類型 默認值>
                屬性的類型:
                    ID:唯一
                    CDATA:文本
                默認值:
                    REQUIRED:必須出現
                    IMPLIED:可以選擇
            類別:
                #PCDATA:文本是一個字符串,不能出現子元素 ,用的時候用(#PCDATA)
            符號:
                +     >=1
                ?     0|1
                *     任意值
                |     選擇
                ()    分組
                ,     順序
DTD約束示例代碼:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE bookstore[
    <!ELEMENT bookstore (book+)>
    <!ELEMENT book (title,author,year,price)>
    <!ELEMENT title (#PCDATA)>
    <!ELEMENT author (#PCDATA)>
    <!ELEMENT year (#PCDATA)>    
    <!ELEMENT price (#PCDATA)>    
    <!ATTLIST book category CDATA #REQUIRED>
    <!ATTLIST title lang CDATA #IMPLIED>
]>
<bookstore>
    <book category="COOKING" >
        <title lang="en" >Everyday Italian</title>
        <author>Giada De Laurentiis</author>
        <year>2005</year>
        <price>30.00</price>
    </book>
    <book category="CHILDREN">
        <title lang="en">Harry Potter</title>
        <author>J K. Rowling</author>
        <year>2005</year>
        <price>29.99</price>
    </book>
    <book category="WEB">
        <title lang="en">Learning XML</title>
        <author>Erik T. Ray</author>
        <year>2003</year>
        <price>39.95</price>
    </book>
</bookstore>
View Code

        2,SCHEMA約束:spring中使用的就是schema約束
            作用:用來替代dtd的,多個schema可以出現一個xml文檔上
            需求:   
                xml 文檔中出現了<table>
                a約束上的---table :桌子 屬性  height width
                b約束上的---table :表格 屬性  rows  cols
            名稱空間:
                作用:用來確定標簽的約束來自於那個約束文檔上
                格式:
                    方式1:xmlns="名稱"
                    方式2:xmlns:別名="名稱"
                例如:
                    table  代表的是桌子
                    b:table 代表的就是表格 
            schema的語法:
                后綴名.xsd
                關聯
                    1.約束文件的關聯 bookstore.xsd
                        xmlns="http://www.w3.org/2001/XMLSchema"-- 固定值,自定義的約束文件可以出現那些標簽
                        targetNamespace="http://www.example.org/bookstore"
                        給當前的xsd起個名稱空間,方便目標xml文件引用,名字可以隨便起,一般使用域名/自定義名稱既可以
                       
                        例如: targetNamespace="bookstore"
                            targetNamespace="http://www.augmentum.com/bookstore"
                       
                        確定一個目標xml根元素
                            <element name="bookstore"></element>
                           
                    2.xml文件的關聯
                        寫根標簽
                        添加schema約束
                            1.xmlns="約束的名稱空間" -- 值為xsd文件上的targetNamespace的內容
                        例如:   
                            xmlns=="http://www.augmentum.com/bookstore"
                           
                            2.xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" :固定的寫法 聲明此文檔是一個
            被schema約束的文件
                            3.確定文檔的位置
                                xsi:schemaLocation="{和xsd文件中的targetNamespace} {xsd文件的路徑}"
                    關聯小結:
                        先有約束文件. .xsd
                            targetNamespace 就是給當前的約束文件起個名字,方便xml使用
                            必須確定根元素
                        后有xml文件.
                            寫根元素
                            添加約束
                                xmlns="名字"  他的值為targetNamespace中起的名稱
                                xsi:schemaLocation="名字 位置"
                    語法:
                        1.確定根元素
                            <element name >
                            name:元素的名稱
                            type:元素的數據類型
                        2.確定元素類型
                            復雜的元素
                                <complexType>
                            簡單的元素 -- 幾乎看不見
                                <simpleType>
                        3.確定順序:
                            <sequence maxOccurs="3">  按次序 相當於  dtd 中,
                            <all> 隨意
                            <choice> 或 相當於dtd中的 |
                           
                            maxOccurs 最大的出現次數    值為unbounded指的是無上限
                            minOccurs 最小的出現次數
                        4.確定屬性
                            <attribute name="category" type="string" use="required" />
                            name :屬性的名稱
                            type:屬性的數據類型
                            use 相當於dtd中 默認值
                                值為required:必須出現
                                值為optional:可選
                               
                        5.若有屬性的元素,內容只是文本
                            <complexType>  --- 指定元素為復雜類型
                                <simpleContent>--- 指定元素是一個簡單的內容,只有文本
                                    <extension base="string">    -- 文本內容進行擴展
                                        <attribute name="lang" type="string" /> -- 添加屬性
                                    </extension>
                                </simpleContent>
                            </complexType>
Schema約束示例:

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" 
    targetNamespace="aaa"
    xmlns:tns="http://www.example.org/bookstore" 
    elementFormDefault="qualified">
    <element name="bookstore" >
        <!--
            1.確定根元素
                <element name >
                name:元素的名稱
                type:元素的數據類型
            2.確定元素類型 
                復雜的元素
                    <complexType>
                簡單的元素 -- 幾乎看不見
                    <simpleType>
            3.確定順序:
                <sequence maxOccurs="3">  按次序 相當於  dtd 中,
                <all> 隨意
                <choice> 或 相當於dtd中的 |
                
                maxOccurs 最大的出現次數    值為unbounded指的是無上限
                minOccurs 最小的出現次數
            4.確定屬性
                <attribute name="category" type="string" use="required" />
                name :屬性的名稱
                type:屬性的數據類型
                use 相當於dtd中 默認值
                    值為required:必須出現
                    值為optional:可選
         -->
        
        <complexType>
            <sequence maxOccurs="unbounded" minOccurs="1">
                <element name="book">
                    <complexType>
                        <sequence>
                            <element name="title">
                                
                            </element>
                            <element name="author" type="string" />
                            <element name="year" type="date" />
                            <element name="price" type="double" />
                        </sequence>
                        <attribute name="category" type="string" use="optional" />
                    </complexType>
                </element>
            </sequence>
        </complexType>
    </element>
</schema>
bookstore.xsd
<?xml version="1.0" encoding="UTF-8"?>
<bookstore xmlns="aaa"
xsi:schemaLocation="aaa bookstore.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
</bookstore>

 
4, xml解析

  獲取xml中的內容
    解析方式:SAX和DOM
    區別:
    sax:逐行的解析,不能增刪改
    dom:把整個文檔加載到內存中,翻譯成一棵樹,就可以進行crud操作
  要求:
    會查詢(獲取)
    DOM4J的解析(只需會查詢操作)
  1.導入包
  2.獲取document
  3.獲取根元素
  4.獲取其他節點
  常用的方法: ☆
    SAXReader reader=new SAXReader();
    Document doc=reader.read(文件路徑);
    獲取根元素:
      Element root=doc.getRootElement();
    獲取其他節點:
    獲取屬性
      List<Element> bookList=root.elements();
    獲取book的屬性
      String value=bookElement.attributeValue("category");
      bookElement.elementText("title");--獲取title的文本內容
    擴展方法:
      獲取book
        Iterator<Element> it = root.elementIterator();
      獲取屬性:
        bookElement.attribute("category").getValue();
      獲取文本
        bookElement.element("title").getText();
示例解析1:
xml代碼

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
    <book category="COOKING">
        <title lang="en">Everyday Italian</title>
        <author>Giada De Laurentiis</author>
        <year>2005</year>
        <price>30.00</price>
    </book>
    <book category="CHILDREN">
        <title lang="en">Harry Potter</title>
        <author>J K. Rowling</author>
        <year>2005</year>
        <price>29.99</price>
    </book>
    <book category="WEB">
        <title lang="en">Learning XML</title>
        <author>Erik T. Ray</author>
        <year>2003</year>
        <price>39.95</price>
    </book>
</bookstore>
View Code

解析代碼:

public static void main(String[] args) throws DocumentException {
    //獲取Document
    Document document = new SAXReader().read("D:/Users/WangMeng/workspace/day08_XML/dtd/bookstore.xml");
    //獲取根元素
    Element root = document.getRootElement();
    //獲取其他節點
    /*獲取其他節點方法一
    List<Element> bookList = root.elements();
    for (Element bookElement : bookList) {
        //獲取屬性
        //String value = bookElement.attributeValue("category");
        //System.out.println(value);
        
        //獲取子標簽的文本內容
        String textValue = bookElement.elementText("title");
        System.out.println(textValue);
    }
    */
    
    //獲取其他節點方法二
    Iterator<Element> it = root.elementIterator();
    while (it.hasNext()) {
        Element bookElement = it.next();
        //獲取屬性
        //String value = bookElement.attribute("category").getValue();
        //獲取元素, 元素內容
        String value = bookElement.element("title").getText();
        System.out.println(value);
    }
}
View Code

X-path解析(獲取)
selectNodes(string):獲取集合 //book
selectSingleNode(string):獲取的單一的元素,若匹配的是一個集合的話,只取第一個
使用之前導入 jaxen-1.1-beta-6.jar
關於Xpath更詳細的可以去w3c文檔看xml中關於xpath的api.

示例解析2:
xml代碼:

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
    <book category="COOKING">
        <title lang="en">Everyday Italian</title>
        <author>Giada De Laurentiis</author>
        <year>2005</year>
        <price>30.00</price>
    </book>
    <book category="CHILDREN">
        <title lang="en">Harry Potter</title>
        <author>J K. Rowling</author>
        <year>2005</year>
        <price>29.99</price>
    </book>
    <book category="WEB">
        <title lang="en">Learning XML</title>
        <author>Erik T. Ray</author>
        <year>2003</year>
        <price>39.95</price>
    </book>
</bookstore>
View Code

解析代碼:

public static void main(String[] args) throws DocumentException
{
    //獲取Document
    Document document = new SAXReader().read("D:/Users/WangMeng/workspace/day08_XML/dtd/bookstore.xml");
    
    //獲取category="WEB"的book元素
    /*
     * 路徑匹配: /a/b/c
     * 元素匹配 : //c
     * 屬性匹配: //c[@屬性='屬性值']
     * 含有子元素: //c[d]
     * 
     * 
     */
    //Element bookElement = (Element)document.selectSingleNode("//book[@category='WEB']");
    Element bookElement = (Element)document.selectSingleNode("//book[price > 35]");
    System.out.println(bookElement.attributeValue("category"));
}
View Code

關於xml的內容就到這里了, 相信看完這些內容 以后再也不擔心xml的約束以及解析了. 

 


免責聲明!

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



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