解讀XML文檔的基本操作_Xml教程

      編輯Tag賺U幣
      教程Tag:暫無Tag,歡迎添加,賺取U幣!

      推薦:對于任意的XML的遍歷
      class test { private static string root; public static void showXML(string path) { XmlDocument xd = new XmlDocument();

      已知有一個XML文檔(bookstore.xml)如下:

      <?xml version="1.0" encoding="gb2312"?>
      <bookstore>
      <book genre="fantasy" ISBN="2-3631-4">
      <title>Oberons Legacy</title>
      <author>Corets, Eva</author>
      <price>5.95</price>
      </book>
      </bookstore>

      1、往<bookstore>節點中插入一個<book>節點:

      XmlDocument xmlDoc=new XmlDocument();
      xmlDoc.Load("bookstore.xml");
      XmlNode root=xmlDoc.SelectSingleNode("bookstore");//查找<bookstore>
      XmlElement xe1=xmlDoc.CreateElement("book");//創建一個<book>節點
      xe1.SetAttribute("genre","李贊紅");//配置該節點genre屬性
      xe1.SetAttribute("ISBN","2-3631-4");//配置該節點ISBN屬性

      XmlElement xesub1=xmlDoc.CreateElement("title");
      xesub1.InnerText="CS從入門到精通";//配置文本節點
      xe1.AppendChild(xesub1);//添加到<book>節點中
      XmlElement xesub2=xmlDoc.CreateElement("author");
      xesub2.InnerText="候捷";
      xe1.AppendChild(xesub2);
      XmlElement xesub3=xmlDoc.CreateElement("price");
      xesub3.InnerText="58.3";
      xe1.AppendChild(xesub3);

      root.AppendChild(xe1);//添加到<bookstore>節點中
      xmlDoc.Save("bookstore.xml");


      //================
      結果為:

      <?xml version="1.0" encoding="gb2312"?>
      <bookstore>
      <book genre="fantasy" ISBN="2-3631-4">
      <title>Oberons Legacy</title>
      <author>Corets, Eva</author>
      <price>5.95</price>
      </book>
      <book genre="李贊紅" ISBN="2-3631-4">
      <title>CS從入門到精通</title>
      <author>候捷</author>
      <price>58.3</price>
      </book>
      </bookstore>

      2、修改節點:將genre屬性值為“李贊紅“的節點的genre值改為“update李贊紅”,將該節點的子節點<author>

      的文本修改為“亞勝”。

      XmlNodeList nodeList=xmlDoc.SelectSingleNode("bookstore").ChildNodes;//獲取bookstore節點的任何子節


      foreach(XmlNode xn in nodeList)//遍歷任何子節點
      {
      XmlElement xe=(XmlElement)xn;//將子節點類型轉換為XmlElement類型
      if(xe.GetAttribute("genre")=="李贊紅")//假如genre屬性值為“李贊紅”
      {
      xe.SetAttribute("genre","update李贊紅");//則修改該屬性為“update李贊紅”

      XmlNodeList nls=xe.ChildNodes;//繼續獲取xe子節點的任何子節點
      foreach(XmlNode xn1 in nls)//遍歷
      {
      XmlElement xe2=(XmlElement)xn1;//轉換類型
      if(xe2.Name=="author")//假如找到
      {
      xe2.InnerText="亞勝";//則修改
      break;//找到退出來就能夠了
      }
      }
      break;
      }
      }

      xmlDoc.Save("bookstore.xml");//保存。

      //=================

      最后結果為:

      <?xml version="1.0" encoding="gb2312"?>
      <bookstore>
      <book genre="fantasy" ISBN="2-3631-4">
      <title>Oberons Legacy</title>
      <author>Corets, Eva</author>
      <price>5.95</price>
      </book>
      <book genre="update李贊紅" ISBN="2-3631-4">
      <title>CS從入門到精通</title>
      <author>亞勝</author>
      <price>58.3</price>
      </book>
      </bookstore>

      3、刪除 <book genre="fantasy" ISBN="2-3631-4">節點的genre屬性,刪除 <book genre="update李贊紅"

      ISBN="2-3631-4">節點。

      XmlNodeList xnl=xmlDoc.SelectSingleNode("bookstore").ChildNodes;

      foreach(XmlNode xn in xnl)
      {
      XmlElement xe=(XmlElement)xn;

      if(xe.GetAttribute("genre")=="fantasy")
      {
      xe.RemoveAttribute("genre");//刪除genre屬性
      }
      else if(xe.GetAttribute("genre")=="update李贊紅")
      {
      xe.RemoveAll();//刪除該節點的全部內容
      }
      }
      xmlDoc.Save("bookstore.xml");

      //====================

      最后結果為:

      <?xml version="1.0" encoding="gb2312"?>
      <bookstore>
      <book ISBN="2-3631-4">
      <title>Oberons Legacy</title>
      <author>Corets, Eva</author>
      <price>5.95</price>
      </book>
      <book>
      </book>
      </bookstore>

      4、顯示任何數據。


      XmlNode xn=xmlDoc.SelectSingleNode("bookstore");

      XmlNodeList xnl=xn.ChildNodes;

      foreach(XmlNode xnf in xnl)
      {
      XmlElement xe=(XmlElement)xnf;
      Console.WriteLine(xe.GetAttribute("genre"));//顯示屬性值
      Console.WriteLine(xe.GetAttribute("ISBN"));

      XmlNodeList xnf1=xe.ChildNodes;
      foreach(XmlNode xn2 in xnf1)
      {
      Console.WriteLine(xn2.InnerText);//顯示子節點點文本
      }
      }

      public static string DataToXml(string _ip,string _xmlType,bool _issavexml,string

      _contenttype,string _message,string _sendtime,string _toip)
      {
      //return null;
      DataParser dp = new DataParser();
      dp.Message = _message;
      dp.IP = _ip;
      dp.XmlType = _xmlType;
      dp.isSaveXml = _issavexml;
      dp.ContentType = _contenttype;
      dp.Sendtime = _sendtime;
      dp.Toip = _toip;
      XmlDocument doc = new XmlDocument();
      XmlDeclaration newDec = doc.CreateXmlDeclaration("1.0",null,null);
      doc.AppendChild(newDec);
      XmlElement newRoot = doc.CreateElement("Requests");
      doc.AppendChild(newRoot);
      XmlElement newtitle = doc.CreateElement("Request");
      newtitle.SetAttribute("time", dp.Sendtime);
      newRoot.AppendChild(newtitle);
      XmlElement from = doc.CreateElement("from");
      from.SetAttribute("ip", dp.IP);
      from.SetAttribute("type", dp.XmlType);
      from.SetAttribute("ctntype", dp.ContentType);
      XmlNode xnfrom = doc.CreateNode(XmlNodeType.CDATA, "content", null);
      xnfrom.InnerText = _message;
      from.PrependChild(xnfrom);
      // from.InnerText = _message;
      newtitle.AppendChild(from);
      XmlElement to = doc.CreateElement("to");
      (to as XmlElement).SetAttribute("ip", dp.Toip);
      newtitle.AppendChild(to);
      return doc.OuterXml;
      }

      /// <summary>
      /// 數據解包
      /// 將xml解析成UserConnection對象
      /// </summary>
      /// <returns>UserConnection</returns>
      public static DataParser[] XmlToData(string outxml)
      {
      //return null;
      DataParser[] dp = null;
      try
      {
      XmlDocument doc = new XmlDocument();
      doc.LoadXml(outxml);
      XmlNode rootnode = doc.SelectSingleNode("Requests");
      XmlNodeList bodynodelist = rootnode.SelectNodes("Request");
      dp = new DataParser[bodynodelist.Count];
      foreach (XmlNode sn in bodynodelist)
      {
      int i = 0;
      XmlElement xe = (XmlElement)sn;
      XmlNode xn = sn.SelectSingleNode("from");
      dp[i] = new DataParser();
      dp[i].IP = (xn as XmlElement).Attributes["ip"].Value;

      // dp[i].IP = (xn as XmlElement).GetAttribute("ip");
      dp[i].Message = xn.InnerText;
      dp[i].ContentType = (xn as XmlElement).Attributes["ctntype"].Value;
      dp[i].XmlType = (xn as XmlElement).Attributes["type"].Value;
      dp[i].Sendtime = (sn as XmlElement).Attributes["time"].Value;
      XmlNode xn2 = sn.SelectSingleNode("to");
      dp[i].Toip = (xn2 as XmlElement).Attributes["ip"].Value;
      i ;

      }


      }
      catch (Exception err)
      {
      ChatCommon.Common.ExceptionHand.HandleErr(err.ToString());
      }
      return dp;
      }

       

      using System;
      using System.Collections.Generic;
      using System.Text;
      using System.Xml;
      namespace XmlDOM
      {
      class Program
      {
      static void Main(string[] args)
      {
      XmlDocument doc = new XmlDocument();
      XmlDeclaration xd = doc.CreateXmlDeclaration("1.0", null, null);
      doc.AppendChild(xd);
      XmlElement xe = doc.CreateElement("bookstore");
      doc.AppendChild(xe);
      XmlElement xr = doc.CreateElement("book");
      xr.SetAttribute("publish", "thinkbank 1");
      xr.InnerText = "c#基礎";
      xe.AppendChild(xr);
      XmlElement xr2 = doc.CreateElement("book");
      xr2.SetAttribute("publish", "thinkbank 1");
      xr2.InnerText = "j#基礎";
      xe.AppendChild(xr2);
      string xml = doc.OuterXml;
      XmlDocument doc2 = new XmlDocument();
      doc2.LoadXml(xml);
      //doc.Save(@"d:/33.xml");
      //XmlDocument doc = new XmlDocument();
      //doc.Load(@"d:/33.xml");
      ////XmlNode xn = doc.SelectSingleNode("bookstore");
      XmlNodeList xnlist = doc2.SelectNodes("//book");
      foreach (XmlNode mynode in xnlist)
      {
      Console.WriteLine(mynode.InnerText);
      }

      }
      }
      }

       

      XPath 應用:


      XML 文檔對象模型 (DOM)
      能夠以編程方式讀取、處理和修改 XML 文檔。

      XPath 表達式
      XPath 表達式使用路徑表示法(與 URL 中使用的路徑表示法類似)尋址 XML 文檔的各個部分。表達式計算為生

      成子元素集、布爾值、數字或字符串類型的對象。

      URL與XPath 表達式比較
      URL: 由文件系統中的文件夾和文件組成的層次結構。
      每個級別具有唯一名稱的文件。URL 總是標識單個文件。
      相對特定文件夾(稱為“當前文件夾”)進行計算。
      XPath: 由 XML 文檔中的元素和其他元素組成的層次結構。
      每個級別的元素名可能不是唯一的。XPath 表達式標識所有匹配的元素集。
      相對特定元素(稱為表達式的“上下文”)進行計算。

      基本 XPath 表達式 (判斷是誰的集合!!)
      1.當前上下文
      以句點和正斜杠 (./) 作為前綴的表達式明確使用當前上下文作為上下文。例如,以下表達式引用當前上下文

      中的所有 <author> 元素:
      ./author
      注意,此表達式等效于以下表達式:
      author

      2.文檔根
      以正斜杠 (/) 為前綴的表達式使用文檔樹的根作為上下文。例如,以下表達式引用此文檔根的 <bookstore>

      元素:
      /bookstore
      3.根元素
      使用正斜杠后接星號 (/*) 的表達式將使用根元素作為上下文。例如,以下表達式查找文檔的根元素:
      /*
      4.遞歸下降
      用雙正斜杠 (//) 的表達式指示可以包括零個或多個層次結構級別的搜索。如果此運算符出現在模式的開頭,

      上下文相對于文檔的根。例如,以下表達式引用當前文檔中任意位置的所有 <author> 元素:
      //author
      .// 前綴指示上下文從層次結構中當前上下文所指示的級別開始。
      5.特定元素
      以元素名開頭的表達式引用特定元素的查詢,從當前上下文節點開始。例如,以下表達式引用當前上下文節點

      中 <images> 元素內的 <background.jpg> 元素:
      images/background.jpg
      以下表達式引用當前上下文節點中 <bookstore> 元素內的 <book> 元素的集合:
      bookstore/book
      以下表達式引用當前上下文節點中的所有 <first.name> 元素:
      first.name
      XPath 表達式是使用下表中所示的運算符和特殊字符構造的。
      運算符和特殊字符:
      / 子運算符;選擇左側集合的直接子級。此路徑運算符出現在模式開頭時,表示應從根節點選擇該子級。
      // 遞歸下降;在任意深度搜索指定元素。此路徑運算符出現在模式開頭時,表示應從根節點遞歸下降。
      . 指示當前上下文。
      .. 當前上下文節點的父級。
      * 通配符;選擇所有元素,與元素名無關。
      @ 屬性;屬性名的前綴。
      @* 屬性通配符;選擇所有屬性,與名稱無關。
      : 命名空間分隔符;將命名空間前綴與元素名或屬性名分隔。
      ( ) 為運算分組,明確設置優先級。
      [ ] 應用篩選模式。
      [ ] 下標運算符;用于在集合中編制索引。
      執行加法。
      - 執行減法。
      div 根據 IEEE 754 執行浮點除法。
      * 執行乘法。
      mod 從截斷除法返回余數。

      優先級 字符 用途
      1 ( ) 分組
      2 [ ] 篩選器
      3 / // 路徑運算

      分組運算符()僅適用于頂級路徑表達式。
      例如:
      (//author/degree | //author/name) 是有效的分組運算
      //author/(degree | name) 不是有效的分組運算
      篩選模式運算符 [] 的優先級高于路徑運算符(/ 和 //)。
      例如:
      //comment()[3]
      選擇相對于文檔中任意位置comment的父級索引等于3的所有comment,可以返回多個備注

      (//comment())[3]
      選擇相對于父級的所有comment集中的第三個comment,只能返回一個備注。

      author/first-name
      當前上下文節點的 <author> 元素中的所有 <first-name> 元素。

      bookstore//title
      <bookstore> 元素中更深的一級或多級(任意子代)的所有 <title> 元素。注意,此表達式與以下模式

      bookstore/*/title 不同。

      bookstore/*/title
      屬于 <bookstore> 元素的孫級的所有 <title> 元素。

      bookstore//book/excerpt//emph
      <book> 元素的 <excerpt> 子級中的任意位置和 <bookstore> 元素中的任意位置的所有 <emph> 元素:

      .//title
      當前上下文中更深的一級或多級的所有 <title> 元素。注意,本質上只有這種情況需要句點表示法。
      通配符
      通過使用通配符 * 集合,不使用元素名即可引用元素。* 集合引用作為當前上下文的子級的所有元素,與名稱無

      關。
      例如:
      author/*
      <author> 元素的所有元素子級。

      book/*/last-name
      所有作為 <book> 元素的孫級的 <last–name> 元素。

      */*
      當前上下文的所有孫級元素。

      my:book
      my 命名空間中的 <book> 元素。

      my:*
      my 命名空間中的所有元素。
      屬性
      XPath 使用 @ 符號表示屬性名。屬性和子元素應公平對待,兩種類型之間的功能應盡可能相當。
      例如:
      @style
      當前元素上下文的 style 屬性。

      price/@exchange
      當前上下文中 <price> 元素的 exchange 屬性。

      book/@style
      所有 <book> 元素的 style 屬性。

      @*
      當前上下文節點的所有屬性。

      @my:*
      my 命名空間中的所有屬性。不包括 my 命名空間中的元素的未限定屬性。

      注意:
      屬性不能包含子元素,所以,如果對屬性應用路徑運算符,將出現語法錯誤。此外,不能對屬性應用索引,

      因為根據定義,不為屬性定義任何順序。
      price/@exchange/total
      比較
      運算符:

      and 邏輯與
      or 邏輯或
      not() 非
      = 相等
      != 不相等
      &lt; 小于
      &lt;= 小于或等于
      &gt; 大于
      &lt;= 大于或等于
      | 集運算;返回兩個節點集的聯合


      例如:
      author[last-name = "Bob"]
      至少包含一個值為 Bob 的 <last-name> 元素的所有 <author> 元素。

      author[last-name[1] = "Bob"]
      第一個 <last-name> 子元素的值為 Bob 的所有 <author> 元素。

      author/degree[@from != "Harvard"]
      包含 from 屬性不等于 "Harvard" 的 <degree> 元素的所有 <author> 元素。

      author[last-name = /editor/last-name]
      包含與根元素下 <editor> 元素中的 <last-name> 元素相同的 <last-name> 元素的所有 <author> 元素。

      author[. = "Matthew Bob"]
      所有字符串值為 Matthew Bob 的 <author> 元素。
      集運算
      Union (|) 運算符
      |(即 union)運算符返回兩個操作數的聯合,操作數必須是節點集。例如,//author | //publisher 返回的節

      點集結合了所有 //author 節點和所有 //publisher 節點。


      例如:
      first-name | last-name
      包含當前上下文中的 <first-name> 和 <last-name> 元素的節點集。

      (bookstore/book | bookstore/magazine)
      包含 <bookstore> 元素中的 <book> 或 <magazine> 元素的節點集。

      book | book/author
      包含 <book> 元素中的所有 <book> 元素和所有 <author> 元素的節點集。

      (book | magazine)/price
      包含 <book> 或 <magazine> 元素的所有 <price> 元素的節點集。


      篩選器和篩選模式

      通過將篩選子句 [pattern] 添加到集合中,可以對任何集合應用約束和分支。篩選器類似于 SQL WHERE 子句。

      篩選器中包含的模式稱為“篩選模式”。

      例如:
      book[excerpt]
      至少包含一個 <excerpt> 元素的所有 <book> 元素。

      book[excerpt]/title
      至少包含一個 <excerpt> 元素的 <book> 元素內的所有 <title> 元素。

      book[excerpt]/author[degree]
      至少包含一個 <degree> 元素并且在至少包含一個 <excerpt> 元素的 <book> 元素內的所有 <author> 元素

      book[author/degree]
      至少包含一個 <author> 元素并且該元素至少包含一個 <degree> 子元素的 <book> 所有元素。

      book[excerpt][title]
      至少包含一個 <excerpt> 元素以及至少包含一個 <title> 元素的 <book> 所有元素。

      分享:如何從xml中獲取城市,省份名稱
      最近沒事,寫了個在項目經常要取城市或省份名的方法,所以改成了一個類.方便以后調用//********************************************************************************//*

      來源:模板無憂//所屬分類:Xml教程/更新時間:2009-08-15
      相關Xml教程