JAVA解析XML與C#解析XML(DOM,SAS,JDOM,DOM4J)

  • [一、XML解析總覽]
    本章導航-----XML解析思惟導圖
    uploading-image-134101.png
    XML的解析方式分爲四種:一、DOM解析;二、SAX解析;三、JDOM解析;四、DOM4J解析。其中前兩種屬於基礎方法,是官方提供的平臺無關的解析方式;後兩種屬於擴展方法,它們是在基礎的方法上擴展出來的,只適用於java平臺。java

    a:DOM解析---採用dom解析,會將xml文檔所有載入到內存中,而後將xml文檔中的全部內容轉換爲tree上的節點(對象);
    優勢:能夠隨機解析訪問文檔中的數據、能夠修改文件、能夠建立xml文件;
    缺點:適合解析小文件,對內存要求高node

    b:SAX解析---基於事件處理的機制;sax解析xml文件時,遇到開始標籤,結束標籤,開始解析文件,文件解析結束,字符內容,空白字符等都會觸發各自的方法;
    優勢:適合解析大文件,對內存要求不高;輕量級的解析數據方式,效率更高
    缺點:不能隨機解析;不能修改XML文件,只能進行查詢;編碼比較麻煩,很難同時訪問XML文件中的多處不一樣數據;程序員

    c:JDOM解析---JDOM 直接爲JAVA編程服務。它利用更爲強有力的JAVA語言的諸多特性(方法重載、集合概念以及映射),把SAX和DOM的功能有效地結合起來,簡化了DOM讀取操做的過程,簡化了輸出DOM樹的操做。
    特色:Jdom同時具備DOM修改文件的優勢和SAX讀取快速的優勢;僅使用具體類,而不使用接口;API大量使用了Collections類。web

    d:DOM4J解析---DOM4J解析xml文件比DOM和SAX還有JDOM都要更強大.可是DOM4J並非Java官方提供的操做接口,要使用DOM4J能夠到官網中下載DOM4J.jar包,將jar包導入到項目中便可使用.
    特色:DOM4j解析的好處在與簡化了,xml文檔數據的增刪改查和xml文檔的輸出操做,方便了開發人員的操做,便於理解.數據庫

  • [二、XML有什麼做用]
    本章導航-----XML的重要性
    uploading-image-401221.png
    [XML出現的地方]apache

    XML不是一種可執行的程序,它只是一種數據的載體,不過因爲這種數據載體的格式簡單易懂,加上良好的擴充性能,使得XML的用處十分普遍。從框架的各類配置文件到Ajax中的數據交換,再到Web Service的推行、SOA理念的應用等等,都離不開XML。編程

    [XML的做用]api

    第一: 數據傳輸須要必定的格式(數據的可讀性;未來的擴展;未來的維護)
    第二: 配置文件,以前使用的.properties資源文件中描述的信息不豐富
    第三: 保存數據,充當小型的數據庫,保存數據通常是使用數據庫保存,或者使用通常的文件保存,這個時候也能夠選擇XML文件,由於XML能夠描述複雜的數據關係。從普通文件中讀取數據的速度確定是比從數據庫中讀取數據的速度快,只不過這樣不是很安全而已.數組

  • [三、C#的DOM解析XML]
    本章導航-----C#的DOM解析
    uploading-image-714291.png
    [涉及到C#中具體的類及方法]緩存

    在System.XML命名空間中有如下幾個用於XML的類:
    a:XMLTextReader—提供以快速、單向、無緩衝的方式存取XML數據。(單向意味着你只能從前日後讀取XML文件,而不能逆向讀取)

    b:XMLValiddatingReader—與XMLTextReader類一塊兒使用,提供驗證DTD、XDR和XSD構架的能力。

    c:XMLDocument—遵循W3C文檔對象模型規範的一級和二級標準,實現XML數據隨機的、有緩存的存取。一級水平包含了DOM的最基本的部分,而二級水平增長多種改進,包括增長了對名稱空間和級連狀圖表(CSS)的支持。

    d:XMLTextWriter—生成遵循W3C XML1.0規範的XML文件。

    no_1:XmlDocument:加載xml文檔.eg:XmlDocument document = new XmlDocument();document.load(@"D:\C#\books.xml");

    no_2:XmlElement:用於返回一個元素實例.e.g:XmlElement element = document.DocumentElement; //經常使用來返回一個根節點

    XmlElement類包含許多方法和屬性,能夠處理樹的節點和屬性
    1)FirstChild:返回根元素節點後的第一個子節點
    2)LastChild:返回根元素節點後的最後一個子節點
    3)ParentNode:返回當前元素的父節點
    4)NextSibling:返回當前節點的父節點下的下一個節點
    5)HasChildNodes:用來檢查當前元素是否有子元素
    no_3:XmlText:表示開關標記之間的文本,是特殊的節點,屬性有:

    1)InnerText:獲取當前節點範圍內的全部子節點的文本鏈接起來的字符串
    2)InnerXml:獲取當前節點範圍內的全部子節點的文本鏈接起來的字符串,包含標記
    no_4:XML修改解析

    (1)建立節點
    建立節點方法:
    1)CreateElement:用來建立XmlDocument類型的節點
    2)CreateAttribute:用來建立XmlAttribute類型的節點
    3)CreateTextNode:用來建立XmlTextNode類型的節點
    4)CreateNode:用來建立任意類型的節點,包含上述三種以及其餘

    (2)建立節點後添加操做:
    1)AppendChild:把建立的節點類型追加到XmlNode類型或其餘派生類型的節點後
    2)InsertAfter:將新節點插入到特定的位置
    3)InsertBefore:將新節點插入到特定位置

    (3)刪除節點
    1)RemoveChild:刪除當前節點範圍內的一個指定的子節點
    2)RemoveAll:刪除該節點範圍內的全部子節點

    (4)修改節點
    1)ReplaceChild:用新子節點替換舊子節點
    no_5:XML查詢解析

    (1)使用XmlDocument 方法
    XmlDocument document = new XmlDocument();
    document.Load(filePath);
    XmlNodeList list = document.GetElementsByTagName("book");
    foreach (XmlNode node in list)
    {
    listBox1.Items.Add(node.Name);//listBox1類型是ListBox
    }
    (2)使用XPath選擇特定的節點的方法
    1)SelectSingleNode:用來選擇一個節點,若是有多個,則返回第一個節點
    2)SelectNodes:返回一個節點的集合,類型是XmlNodesList;選擇特定的節點的方法參數XPath;XPath是XML文檔的查詢語言
    具體參考Microsoft C#API
    [代碼示例]

    using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;
      using System.Xml;
    
      namespace ConsoleApp1
      {
      	class Program
      	{
      		static void Main(string[] args)
      		{
          		try
          		{
              	//xml文件存儲路徑
              	string myXMLFilePath = "C:\\MyComputers.xml";
              	//生成xml文件
              	GenerateXMLFile(myXMLFilePath);
              	//遍歷xml文件的信息
              	GetXMLInformation(myXMLFilePath);
              	//修改xml文件的信息
              	ModifyXmlInformation(myXMLFilePath);
              	//向xml文件添加節點信息
              	AddXmlInformation(myXMLFilePath);
              	//刪除指定節點信息
              	DeleteXmlInformation(myXMLFilePath);
          		}
          		catch (Exception ex)
          		{
              	Console.WriteLine(ex.ToString());
          		}
      		}
    
      		private static void GenerateXMLFile(string xmlFilePath)
      		{
          		try
          		{
              	//初始化一個xml實例
              	XmlDocument myXmlDoc = new XmlDocument();
              	//建立xml的根節點
              	XmlElement rootElement = myXmlDoc.CreateElement("Computers");
              	//將根節點加入到xml文件中(AppendChild)
              	myXmlDoc.AppendChild(rootElement);
    
              	//初始化第一層的第一個子節點
              	XmlElement firstLevelElement1 = myXmlDoc.CreateElement("Computer");
              	//填充第一層的第一個子節點的屬性值(SetAttribute)
              	firstLevelElement1.SetAttribute("ID", "11111111");
              	firstLevelElement1.SetAttribute("Description", "Made in China");
              	//將第一層的第一個子節點加入到根節點下
              	rootElement.AppendChild(firstLevelElement1);
              	//初始化第二層的第一個子節點
              	XmlElement secondLevelElement11 = myXmlDoc.CreateElement("name");
              	//填充第二層的第一個子節點的值(InnerText)
              	secondLevelElement11.InnerText = "Lenovo";
              	firstLevelElement1.AppendChild(secondLevelElement11);
              	XmlElement secondLevelElement12 = myXmlDoc.CreateElement("price");
              	secondLevelElement12.InnerText = "5000";
              	firstLevelElement1.AppendChild(secondLevelElement12);
    
    
              	XmlElement firstLevelElement2 = myXmlDoc.CreateElement("Computer");
              	firstLevelElement2.SetAttribute("ID", "2222222");
              	firstLevelElement2.SetAttribute("Description", "Made in USA");
              	rootElement.AppendChild(firstLevelElement2);
              	XmlElement secondLevelElement21 = myXmlDoc.CreateElement("name");
              	secondLevelElement21.InnerText = "IBM";
              	firstLevelElement2.AppendChild(secondLevelElement21);
              	XmlElement secondLevelElement22 = myXmlDoc.CreateElement("price");
              	secondLevelElement22.InnerText = "10000";
              	firstLevelElement2.AppendChild(secondLevelElement22);
    
              	//將xml文件保存到指定的路徑下
              	myXmlDoc.Save(xmlFilePath);
          		}
          		catch (Exception ex)
          		{
              	Console.WriteLine(ex.ToString());
          		}
      		}
    
      		private static void GetXMLInformation(string xmlFilePath)
      		{
          		try
          		{	
              	//初始化一個xml實例
              	XmlDocument myXmlDoc = new XmlDocument();
              	//加載xml文件(參數爲xml文件的路徑)
              	myXmlDoc.Load(xmlFilePath);
              	//得到第一個姓名匹配的節點(SelectSingleNode):此xml文件的根節點
              	XmlNode rootNode = myXmlDoc.SelectSingleNode("Computers");
              	//分別得到該節點的InnerXml和OuterXml信息
              	string innerXmlInfo = rootNode.InnerXml.ToString();
              	string outerXmlInfo = rootNode.OuterXml.ToString();
              	//得到該節點的子節點(即:該節點的第一層子節點)
              	XmlNodeList firstLevelNodeList = rootNode.ChildNodes;
              	foreach (XmlNode node in firstLevelNodeList)
              	{
                  //得到該節點的屬性集合
                  XmlAttributeCollection attributeCol = node.Attributes;
                  foreach (XmlAttribute attri in attributeCol)
                  {
                      //獲取屬性名稱與屬性值
                      string name = attri.Name;
                      string value = attri.Value;
                      Console.WriteLine("{0} = {1}", name, value);
                  }
                  	  //判斷此節點是否還有子節點
                  	  if (node.HasChildNodes)
                  	  {
                        //獲取該節點的第一個子節點
                        XmlNode secondLevelNode1 = node.FirstChild;
                        //獲取該節點的名字
                        string name = secondLevelNode1.Name;
                        //獲取該節點的值(即:InnerText)
                        string innerText = secondLevelNode1.InnerText;
                        Console.WriteLine("{0} = {1}", name, innerText);
    
                        //獲取該節點的第二個子節點(用數組下標獲取)
                        XmlNode secondLevelNode2 = node.ChildNodes[1];
                        name = secondLevelNode2.Name;
                        innerText = secondLevelNode2.InnerText;
                        Console.WriteLine("{0} = {1}", name, innerText);
                      }
                }
               }
               catch (Exception ex)
               {
                Console.WriteLine(ex.ToString());
               }
           }
    
           private static void ModifyXmlInformation(string xmlFilePath)
           {
          		try
          		{
              	XmlDocument myXmlDoc = new XmlDocument();
              	myXmlDoc.Load(xmlFilePath);
              	XmlNode rootNode = myXmlDoc.FirstChild;
              	XmlNodeList firstLevelNodeList = rootNode.ChildNodes;
              	foreach (XmlNode node in firstLevelNodeList)
              	{
                  //修改此節點的屬性值
                  if (node.Attributes["Description"].Value.Equals("Made in USA"))
                  {
                      node.Attributes["Description"].Value = "Made in HongKong";
                  }
              	}
              	//要想使對xml文件所作的修改生效,必須執行如下Save方法
              	myXmlDoc.Save(xmlFilePath);
          		}
          		catch (Exception ex)
          		{
              		Console.WriteLine(ex.ToString());
          		}
    
      		}
    
      		private static void AddXmlInformation(string xmlFilePath)
      		{
          		try
          		{
              	XmlDocument myXmlDoc = new XmlDocument();
              	myXmlDoc.Load(xmlFilePath);
              	//添加一個帶有屬性的節點信息
              	foreach (XmlNode node in myXmlDoc.FirstChild.ChildNodes)
              	{
                  XmlElement newElement = myXmlDoc.CreateElement("color");
                  newElement.InnerText = "black";
                  newElement.SetAttribute("IsMixed", "Yes");
                  node.AppendChild(newElement);
              	}
              		//保存更改
              		myXmlDoc.Save(xmlFilePath);
          		}
          		catch (Exception ex)
          		{
              		Console.WriteLine(ex.ToString());
          		}
      		}
    
      		private static void DeleteXmlInformation(string xmlFilePath)
      		{
          		try
          		{
              	XmlDocument myXmlDoc = new XmlDocument();
              	myXmlDoc.Load(xmlFilePath);
              	foreach (XmlNode node in myXmlDoc.FirstChild.ChildNodes)
              	{
                  //記錄該節點下的最後一個子節點(簡稱:最後子節點)
                  XmlNode lastNode = node.LastChild;
                  //刪除最後子節點下的左右子節點
                  lastNode.RemoveAll();
                  //刪除最後子節點
                  node.RemoveChild(lastNode);
              	}
              	//保存對xml文件所作的修改
              	myXmlDoc.Save(xmlFilePath);
          		}
          		catch (Exception ex)
          		{
              		Console.WriteLine(ex.ToString());
          		}
      		}
      	}
  • [C#的SAX解析XML]
    本章導航-----C#的SAX解析
    uploading-image-856929.png

    • [準備工做]

      .net封裝了對SAX的具體實現,能夠經過調用裏面的方法,進行具體的代碼操做。第三方下載地址

  • [JAVA的JAXP之DOM解析XML]
    本章導航-----JAVA中的DOM解析
    uploading-image-514651.png

    • [JAXP介紹(Java API for XMLProcessing)]

      JAXP 是J2SE的一部分,它由javax.xml、org.w3c.dom 、org.xml.sax 包及其子包組成.在 javax.xml.parsers 包中,定義了幾個工廠類,程序員調用這些工廠類,能夠獲得對xml文檔進行解析的 DOM 或 SAX 的解析器對象。

    • [具體步驟]

      step一、建立解析器工廠對象 DocumentBuildFactory;
      step二、由解析器工廠對象建立解析器對象DocumentBuilder;
      step三、由解析器對象對指定XML文件進行解析,構建相應的DOM樹,建立Document對象;
      step四、以Document對象爲起點對DOM樹的節點進行查詢;
      step五、使用Document的getElementsByTagName方法獲取元素名稱,生成一個NodeList集;
      step六、遍歷集合;

    • [具體代碼]

    要解析的xml文件

    <?xml version='1.0' encoding='gb2312' ?>
    <root>
    <hang>
        <產品惟一ID>產品惟一ID</產品惟一ID>
        <通用名>通用名</通用名>
        <商品名>商品名</商品名>
        <劑型>劑型</劑型>
        <批准文號>批准文號</批准文號>
        <規格>規格</規格>
        <包裝說明>包裝說明</包裝說明>
        <包裝單位>包裝單位</包裝單位>
        <生產企業>生產企業</生產企業>
        <大包裝轉換比>大包裝轉換比</大包裝轉換比>
        <中包裝轉換比>中包裝轉換比</中包裝轉換比>
        <備註>備註</備註>
        <庫存>庫存</庫存>
        <供應價>供應價</供應價>
        <是否上架>是否上架</是否上架>
    </hang>
    <hang>
        <產品惟一ID>a121</產品惟一ID>
        <通用名>b12</通用名>
        <商品名>c231</商品名>
        <劑型>dewrwer</劑型>
        <批准文號>e324324</批准文號>
        <規格>f45645</規格>
        <包裝說明>g4543</包裝說明>
        <包裝單位>hq324e2</包裝單位>
        <生產企業>i76</生產企業>
        <大包裝轉換比>j453</大包裝轉換比>
        <中包裝轉換比>k4r43r</中包裝轉換比>
        <備註>le4tr4</備註>
        <庫存>mq3e2</庫存>
        <供應價>nefrw</供應價>
        <是否上架>o56</是否上架>
    </hang>
       </root>

    具體的解析代碼

    import java.io.*;//導入java.io包下的全部類
      import org.w3c.dom.*;//使用org.w3c.dom操做XML文件 
      import org.xml.sax.SAXException;//使用org.xml.sax.SAXException讀取文件
      import javax.xml.parsers.*; //導入 javax.xml.parsers包下的全部類
      public class Test{//類名
      	public static void main(String[] args){//程序主入口函數,帶命令行參數
      		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();//建立DOM模式的解析器工廠對象
      		try{//try代碼塊,當發生異常時會轉到catch代碼塊中
          		DocumentBuilder builder=factory.newDocumentBuilder();//獲得一個DOM解析器對象  
          		Document doc=builder.parse(new File("D:\\test\\XML.xml"));//打開指定路徑下的xml文件  
          		NodeList nl=doc.getElementsByTagName("hang");//得到<hang>文件的值  
          		for (int i=0; i < nl.getLength(); i++){//for循環的條件
              		System.out.println(doc.getElementsByTagName("產品惟一ID").item(i).getFirstChild().getNodeValue());//獲取「產品惟一ID」的信息   
              		System.out.println(doc.getElementsByTagName("通用名").item(i).getFirstChild().getNodeValue());//獲取「通用名」的信息   
              		System.out.println(doc.getElementsByTagName("商品名").item(i)  
                      .getFirstChild().getNodeValue());//獲取「商品名」的信息   
              		System.out.println(doc.getElementsByTagName("劑型").item(i)  
                      .getFirstChild().getNodeValue());//獲取「劑型」的信息 
              		System.out.println(doc.getElementsByTagName("批准文號").item(i)  
                      .getFirstChild().getNodeValue());//獲取「批准文號」的信息 
              		System.out.println(doc.getElementsByTagName("規格").item(i)  
                      .getFirstChild().getNodeValue());//獲取「規格」的信息 
              		System.out.println(doc.getElementsByTagName("包裝說明").item(i)  
                      .getFirstChild().getNodeValue());//獲取「包裝說明」的信息 
              		System.out.println(doc.getElementsByTagName("包裝單位").item(i)  
                      .getFirstChild().getNodeValue());//獲取「包裝單位」的信息 
              		System.out.println(doc.getElementsByTagName("生產企業").item(i)  
                      .getFirstChild().getNodeValue());//獲取「生產企業」的信息 
              		System.out.println(doc.getElementsByTagName("大包裝轉換比").item(i)  
                      .getFirstChild().getNodeValue());//獲取「大包裝轉換比」的信息 
              		System.out.println(doc.getElementsByTagName("中包裝轉換比").item(i)  
                      .getFirstChild().getNodeValue());//獲取「中包裝轉換比」的信息 
              		System.out.println(doc.getElementsByTagName("備註").item(i)  
                      .getFirstChild().getNodeValue());//獲取「備註」的信息 
              		System.out.println(doc.getElementsByTagName("庫存").item(i)  
                      .getFirstChild().getNodeValue());//獲取「庫存」的信息 
              		System.out.println(doc.getElementsByTagName("供應價").item(i)  
                      .getFirstChild().getNodeValue());//獲取「供應價」的信息 
              		System.out.println(doc.getElementsByTagName("是否上架").item(i)  
                      .getFirstChild().getNodeValue());//獲取「是否上架」的信息 
              		System.out.println();//輸出空字符進行格式調整
              	}
          	}
      		catch (ParserConfigurationException e){//當try代碼塊有異常時轉到catch代碼塊
          		e.printStackTrace();//在命令行打印異常信息出錯的位置及緣由
          	}
      		catch (SAXException e){//當try代碼塊有異常時轉到catch代碼塊
          		e.printStackTrace();//在命令行打印異常信息出錯的位置及緣由
          	}
      		catch (IOException e){//當try代碼塊有異常時轉到catch代碼塊
          		e.printStackTrace();//在命令行打印異常信息出錯的位置及緣由  
          	}
    		}
  • [JAVA的JAXP之SAX解析XML]
    本章導航-----JAXP之SAX解析XML
    uploading-image-807598.png

    • [具體步驟]

      step1:獲得xml文件對應的資源,能夠是xml的輸入流,文件和uri
      step2:獲得SAX解析工廠(SAXParserFactory)
      step3:由解析工廠生產一個SAX解析器(SAXParser)
      step4:傳入輸入流和handler給解析器,調用parse()解析

    • [具體代碼]

    建立一個books.xml的配置文件

    <?xml version="1.0" encoding="UTF-8"?>
        <書架>
            <書>
            <書名 name="dddd">java web就業</書名>
            <做者>張三</做者>
            <售價>40</售價> 
            </書>
            <書>
            <書名 name="xxxx">HTML教程</書名>
            <做者>本身</做者>
            <售價>50</售價> 
            </書>
        </書架>

    建立一個javaBean實體類

    package sax;
      public class Book {
      private String name;
      private String author;
      private String price;
      public String getName() {
          return name;
      }
      public void setName(String name) {
          this.name = name;
      }
      public String getAuthor() {
          return author;
      }
      public void setAuthor(String author) {
          this.author = author;
      }
      public String getPrice() {
          return price;
      }
      public void setPrice(String price) {
          this.price = price;
      }
      @Override
      public String toString() {
          return "Book [name=" + name + ", author=" + author + ", price=" + price + "]";
      }
      }

    建立一個ListHandler類,實現ContentHandler相關方法

    新建一個ListHandler類,這個類須要DefaultHandler或者實現ContentHandler接口。該類是SAX解析的核心所在,咱們要重寫如下幾個咱們關心的方法。 
    a:startDocument():文檔解析開始時調用,該方法只會調用一次 
    b:startElement(String uri, String localName, String qName, Attributes attributes):標籤(節點)解析開始時調用
    		參數含義--uri:xml文檔的命名空間;localName:標籤的名字;qName:帶命名空間的標籤的名字;attributes:標籤的屬性集
    c:characters(char[] ch, int start, int length):解析標籤的內容的時候調用
    		參數含義--ch:當前讀取到的TextNode(文本節點)的字節數組;start:字節開始的位置,爲0則讀取所有;length:當前TextNode的長度
    d:endElement(String uri, String localName, String qName):標籤(節點)解析結束後調用 
    e:endDocument():文檔解析結束後調用,該方法只會調用一次
    
    class ListHandler implements ContentHandler{
    
    /**
     * 當讀取到第一個元素時開始作什麼
     */
    
    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes atts) throws SAXException {
        System.out.print("<"+qName);
        for(int i=0;atts!=null&&i<atts.getLength();i++){
            String attName=atts.getQName(i);
            String attValueString=atts.getValue(i);
            System.out.print(" "+attName+"="+attValueString);
            System.out.print(">");
        }
    
    }
    /**
     * 表示讀取到第一個元素結尾時作什麼
     */
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        System.out.print("</"+qName+">");
    
    }
    /**
     * 表示讀取字符串時作什麼
     */
    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        System.out.print(new String(ch,start,length));
    
    }
    
    @Override
    public void setDocumentLocator(Locator locator) {
        // TODO Auto-generated method stub
    
    }
    
    
    @Override
    public void startDocument() throws SAXException {
        // TODO Auto-generated method stub
    
    }
    
    @Override
    public void endDocument() throws SAXException {
        // TODO Auto-generated method stub
    
    }
    
    @Override
    public void startPrefixMapping(String prefix, String uri)
            throws SAXException {
        // TODO Auto-generated method stub
    
    }
    
    @Override
    public void endPrefixMapping(String prefix) throws SAXException {
        // TODO Auto-generated method stub
    
    }
    
    
    @Override
    public void ignorableWhitespace(char[] ch, int start, int length)
            throws SAXException {
        // TODO Auto-generated method stub
    
    }
    
    @Override
    public void processingInstruction(String target, String data)
            throws SAXException {
        // TODO Auto-generated method stub
    
    }
    
    @Override
    public void skippedEntity(String name) throws SAXException {
        // TODO Auto-generated method stub
    
    }
    
      }

    建立程序入口類

    public static void main(String[] args) throws Exception {
      //1.建立解析工廠
      SAXParserFactoryfactory=SAXParserFactory.newInstance();
      //2.獲得解析器
      SAXParser sp=factory.newSAXParser();
      //3獲得解讀器
      XMLReader reader=sp.getXMLReader();
      //設置內容處理器
      reader.setContentHandler(new ListHandler());
      //讀取xml的文檔內容
      reader.parse("src/Book.xml");
    
     }
  • [JAVA的JAXP之JDOM解析XML]
    本章導航-----JDOM解析XML
    uploading-image-859759.png

    • [具體步驟]

      step一、下載jar包,這裏用到的是jdom_1.1.jar
      step二、瞭解jdom_1.1中的主要的類:參考https://blog.csdn.net/vb1088blog/article/details/425532

    • [具體代碼]

      package com.aisino.xml;  
       	import java.io.File;  
       	import java.io.FileWriter;  
       	import java.io.IOException;  
        import java.io.StringReader;  
        import java.util.Iterator;  
        import java.util.List;  
        import org.apache.log4j.Logger;  
        import org.apache.log4j.PropertyConfigurator;  
        import org.jdom.Attribute;  
        import org.jdom.Document;  
        import org.jdom.Element;  
        import org.jdom.JDOMException;  
        import org.jdom.input.SAXBuilder;  
        import org.jdom.output.Format;  
        import org.jdom.output.XMLOutputter;  
        import com.aisino.util.CommonUtil;  
      
        public class XMLParser {  
             static{  
                 //手工加載配置文件  
                 PropertyConfigurator.configureAndWatch("F:\\workspace\\JavaSample\\log4jj.properties");  
             }  
      
       //文件路徑  
       final static String filePath = "F:\\workspace\\JavaSample\\src\\com\\aisino\\xml\\";  
      
       /** 
        * log4j 
        */  
       private static Logger logger = Logger.getLogger(XMLParser.class);  
      
       /** 
        *  
        * 方法功能描述 
        *  
        * @param args 
        * @throws Exception  
        * @return void 
        * @exception 異常描述 
        * @see 
        */  
       public static void main(String[] args) throws Exception {  
           //讀文件到內存  
           Document doc = new XMLParser().readXMLFileToDocument(filePath + "students.xml");  
      
           //寫Document到文件  
           new XMLParser().writeDocumentToFile(doc, filePath + "service.xml");  
      
           //查詢Document  
           new XMLParser().queryXML(doc);  
      
           //添加元素和屬性  
           new XMLParser().addElementAndAttributeToDocument(doc);  
      
           //克隆  
           new XMLParser().copyElementAndToTree(doc);  
      
           //修改XML  
           new XMLParser().updateXML(doc);  
      
           //刪除XML元素和屬性  
           new XMLParser().removeXMLContent(doc);  
      
           new XMLParser().writeDocumentToFile(doc, filePath + "service.xml");  
      
           //內存中的Document->String  
           String docS = new XMLOutputter().outputString(doc);  
           logger.info("docs:" + docS);  
      
           //String->Document  
           Document doc1 = new SAXBuilder().build(new StringReader(docS));  
           new XMLParser().writeDocumentToFile(doc1, "StringToDocument.xml");  
       }  
      
       /** 
        *  
        * 讀xml文件到內存 
        *  
        * @param fileName 文件名 
        * @return  
        * @return Document 
        * @exception 異常描述 
        * @see 
        */  
       public Document readXMLFileToDocument(String fileName) {  
           SAXBuilder saxb = new SAXBuilder();  
      
           try {  
               Document doc = saxb.build(new File(fileName));  
               return doc;  
           } catch (JDOMException e) {  
               //e.printStackTrace();  
           } catch (IOException e) {  
               //e.printStackTrace();  
           }  
      
           return null;  
       }  
      
       /** 
        *  
        * 寫Document到文件 
        *  
        * @param doc      文件 
        * @param fileName 文件名 
        * @return void 
        * @exception 異常描述 
        * @see 
        */  
       public void writeDocumentToFile(Document doc, String fileName) {  
           XMLOutputter xo = new XMLOutputter(Format.getPrettyFormat());  
      
           try {  
               xo.output(doc, new FileWriter(new File(fileName)));  
           } catch (IOException e) {  
               //e.printStackTrace();  
           }  
       }  
      
       /** 
        *  
        * 查詢Document 
        *  
        * @param doc  
        * @return void 
        * @exception 異常描述 
        * @see 
        */  
       @SuppressWarnings("unchecked")  
       public void queryXML(Document doc) {  
           //得到根元素  
           Element rootElement = doc.getRootElement();  
           logger.info("rootElement:" + rootElement);  
      
           //得到根元素的全部孩子元素  
           List rootChildren = rootElement.getChildren();  
           logger.info("rootChildren:" + rootChildren);  
      
           //得到元素的指定名稱的全部元素  
           List studentChildren = rootElement.getChildren("student");  
           logger.info("studentChildren:" + studentChildren);  
      
           //得到指定名稱的第一個元素  
           Element studentChild = rootElement.getChild("student");  
           logger.info("studentChild:" + studentChild);  
      
           //對studnetChildren進行迭代  
           Iterator studentChildIte = studentChildren.iterator();  
           while(studentChildIte.hasNext()){  
               Element studentElement = (Element)studentChildIte.next();  
      
               //得到元素名稱和值  
               String studentName = studentElement.getName();  
               String studentValue = studentElement.getValue();  
               logger.info("studentName:" + studentName);  
               logger.info("studentValue:" + studentValue);  
      
               //得到元素的全部屬性  
               List studentAttributes = studentElement.getAttributes();  
               Attribute currentAttribute = studentElement.getAttribute("studentid");  
               logger.info("currentAttribute:" + currentAttribute);  
      
               if(studentAttributes != null){  
                   Iterator studentAttrIte = studentAttributes.iterator();  
                   while(studentAttrIte.hasNext()){  
                       Attribute currentAttr = (Attribute)studentAttrIte.next();  
      
                       //取得屬性的名稱和值  
                       String curAttrName = currentAttr.getName();  
                       String curAttrValue = currentAttr.getValue();  
                       logger.info("curAttrName:" + curAttrName + " curAttrValue:" + curAttrValue);  
                   }  
               }  
           }  
       }  
      
       /** 
        *  
        * 向XML中添加元素和屬性 
        *  
        * @param doc  
        * @return void 
        * @exception 異常描述 
        * @see 
        */  
       @SuppressWarnings("unchecked")  
       private void addElementAndAttributeToDocument(Document doc) {  
           //根元素  
           Element rootElement = doc.getRootElement();  
      
           //新元素  
           Element companyElement = new Element("aisino");  
           rootElement.addContent(companyElement);  
      
      
           //添加文本值  
           companyElement.setText(CommonUtil.setStrUTF8Encode("航天信息軟件"));  
      
           //【第一種】添加屬性  
           Attribute addressid = new Attribute("addressid",CommonUtil.setStrUTF8Encode("杏石口路甲18號"));  
           Attribute companygender = new Attribute("gender","3");  
           companyElement.setAttribute(addressid);  
           companyElement.setAttribute(companygender);  
      
           //【第二種】添加屬性  
           List companyAttrsList = companyElement.getAttributes();  
           Attribute age = new Attribute("age","5");  
           companyAttrsList.add(age);  
           Attribute people = new Attribute("people","200");  
           companyAttrsList.add(people);  
       }  
      
       /** 
        *  
        * 克隆(複製)XML元素 
        *  
        * @param doc  
        * @return void 
        * @exception 異常描述 
        * @see 
        */  
       private void copyElementAndToTree(Document doc) {  
           Element rootElement = doc.getRootElement();  
      
           //得到指定元素的第一個元素  
           Element studentElement = rootElement.getChild("student");  
      
           //克隆,複製  
           Element cloneStudentElement = (Element)studentElement.clone();  
      
           rootElement.addContent(cloneStudentElement);  
      
           cloneStudentElement.setText("hanhuayi");  
           cloneStudentElement.getAttribute("studentid").setValue("4");  
       }  
      
       /** 
        *  
        * 修改XML 
        *  
        * @param doc  
        * @return void 
        * @exception 異常描述 
        * @see 
        */  
       private void updateXML(Document doc) {  
           Element rootElement = doc.getRootElement();  
      
           //得到指定名稱的第一個孩子元素  
           Element studentElement = (Element)rootElement.getChild("student");  
      
           studentElement.setName("stud");  
           studentElement.setText("newText");  
           studentElement.getAttribute("studentid").setValue("11");  
           studentElement.getAttribute("age").setValue("201");  
       }  
      
       /** 
        *  
        * 刪除XML元素 
        *  
        * @param doc  
        * @return void 
        * @exception 異常描述 
        * @see 
        */  
       private void removeXMLContent(Document doc) {  
           Element rootElement = doc.getRootElement();  
      
           //得到指定元素的第一個元素  
           Element studentElement = rootElement.getChild("student");  
           rootElement.removeContent(studentElement);  
       }  
       }
  • [JAVA的DOM4J解析XML]
    本章導航-----DOM4J解析XML
    uploading-image-538370.png

    • [具體步驟]

      step一、下載jar包(推薦一個jar包的下載網站:https://mvnrepository.com/)
      step二、認識jar包中的主要類:參考https://blog.csdn.net/qq_43386754/article/details/85651049

    • [具體代碼]

      package com.xml.dom4j;
      
      import java.io.FileNotFoundException;
      import java.io.FileOutputStream;
      import java.io.IOException;
      import java.io.UnsupportedEncodingException;
      import java.util.ArrayList;
      import java.util.List;
      
      import org.dom4j.Attribute;
      import org.dom4j.Document;
      import org.dom4j.DocumentException;
      import org.dom4j.Element;
      import org.dom4j.io.OutputFormat;
      import org.dom4j.io.SAXReader;
      import org.dom4j.io.XMLWriter;
      
      import com.xml.dom.Student;
      
      public class Dom4JTest {
          public List<Student> getAllStudent(){
              List<Student> list=new ArrayList<>();
              //構建解析器
              SAXReader dom=new SAXReader();
              try {
                  Document doc=
                          dom.read("src/com/xml/dom/stu.xml");
                  //獲取根標籤
                  Element root=doc.getRootElement();
                  //獲取二級標籤,只獲取元素標籤,忽略掉空白的
                  //文本
                  List<Element> ers=root.elements();
                  for(Element er:ers){
                      Student stu=new Student();
                      //獲取名字
      //              String name=er.getName();
      //              System.out.println(name);
                      //獲取全部的屬性
      //              List<Attribute> attrs=er.attributes();
                      //獲取屬性的值
      //              System.out.println(attrs.get(0).getValue());
                      //獲取單個屬性
                      String id=er.attributeValue("id");
                      stu.setId(Long.parseLong(id));
                      List<Element> sans=er.elements();
                      for(Element san:sans){
                          if(san.getName().equals("name")){
      //                      san.getText();
      //                      san.getTextTrim();
      //                      Object obj=san.getData();
                              stu.setName(san.getText());
                          }else if(san.getName().equals("age")){
                              stu.setAge(Integer.parseInt((String) san.getData()));
                          }
                      }
                      list.add(stu);
                  }
              } catch (DocumentException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
              return list;
          }
          /*
          *添加對象方法
          */
          public void addStudent(Student stu){
              SAXReader sax=new SAXReader();
              try {
                  Document doc=
                          sax.read("src/com/xml/dom/stu.xml");
                  Element root=doc.getRootElement();
                  //添加元素的同時返回當前元素
                  Element stuE=root.addElement("student");
                  //設置元素屬性
                  stuE.addAttribute("id", stu.getId()+"");
                  Element nameE=stuE.addElement("name");
                  //設置文本內容
                  nameE.setText(stu.getName());
                  Element ageE=stuE.addElement("age");
                  ageE.setText(stu.getAge()+"");
                  //移除元素
                  //root.remove(stuE);
                  //第一個參數表示路徑,
                  //第二個參數表示格式
                  //不寫格式輸出的時候,新增長的內容直接一行插入
      //          XMLWriter writer=
      //                  new XMLWriter(
      //                          new FileOutputStream(
      //                                  "src/com/xml/dom/stu.xml"));
                  //OutputFormat format=OutputFormat.createPrettyPrint();
                  //docment中的tree所有轉化爲一行內入寫入
                  OutputFormat format=OutputFormat.createCompactFormat();
                  XMLWriter writer=
                          new XMLWriter(
                                  new FileOutputStream(
                                          "src/com/xml/dom/stu.xml"),format);
                  writer.write(doc);
                  writer.flush();
                  writer.close();
              } catch (DocumentException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              } catch (UnsupportedEncodingException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              } catch (FileNotFoundException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
          }
          /*
          *刪除對象方法
          */
          public void remove(long id){
              SAXReader sax=new SAXReader();
                  try {
                      Document doc=
                              sax.read("src/com/xml/dom/stu.xml");
                      Element root=doc.getRootElement();
                      List<Element> ers=root.elements();
                      for(Element er:ers){
                          String ids=er.attributeValue("id");
                          if(id==Long.parseLong(ids)){
                              er.getParent().remove(er);
                              break;
                          }
                      }
                      OutputFormat format=
                              OutputFormat.createPrettyPrint();
                      XMLWriter writer=
                              new XMLWriter(
                                      new FileOutputStream(
                                              "src/com/xml/dom/stu.xml"),format);
                      writer.write(doc);
                      writer.flush();
                      writer.close();
                  } catch (DocumentException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  } catch (UnsupportedEncodingException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  } catch (FileNotFoundException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  } catch (IOException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  }
          }
          public static void main(String[] args) {
              new Dom4JTest().remove(3);
      //      new Dom4JTest().addStudent(
      //              new Student(3,"briup",55));
      //      List<Student> list=new Dom4JTest().getAllStudent();
      //      for(Student s:list){
      //          System.out.println(s);
      //      }
          }
      }
相關文章
相關標籤/搜索