ADO.NET系列之操作XML(一)

來源:互聯網
上載者:User

標籤:des   style   blog   http   color   使用   

  如題,我們儲存資料的方式有很多種。在ASP.NET中,可以通過js賦值隱藏欄位的方式,也可以通過ViewState,Session這樣的內建對象,還可以通過資料庫的形式。現在經常用到的就是XML了,它的結構靈活,同時佔用的空間很少,也比較容易操作,今天我們就來說說ADO.NET中,如何去操作XML。

  首先我們可以在一個頁面上,放入一個GridView用來顯示讀取的XML的資料(這裡使用的是經典的books.xml,在一些網站上可以下載),同時再放入一個富文字框來顯示特定的節點,還有一個按鈕用於點擊後在文字框中顯示XML特定節點的內容:

  

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="XmlToDataTable.aspx.cs"    Inherits="WebApplication1.XmlToDataTable" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server">    <title></title></head><body>    <form id="form1" runat="server">    <div>        <asp:TextBox ID="txtShow" runat="server" TextMode="MultiLine" Width="100%"></asp:TextBox>        <asp:GridView ID="gvXML" runat="server" AutoGenerateColumns="false">            <Columns>                <asp:BoundField HeaderText="Id" DataField="id" />                <asp:BoundField HeaderText="Author" DataField="author" />                <asp:BoundField HeaderText="Title" DataField="title" />                <asp:BoundField HeaderText="Genre" DataField="genre" />                <asp:BoundField HeaderText="Price" DataField="price" />                <asp:BoundField HeaderText="Publish_date" DataField="publish_date" />                <asp:BoundField HeaderText="Description" DataField="description" />            </Columns>        </asp:GridView>        <asp:Button ID="btnExport" runat="server" Text="匯出XML" OnClick="btnExport_Click" />    </div>    </form></body></html>

  大家可以看到我在GridView中綁定了一些列,而這些列正是我們的XML擁有的一些節點:

  

<?xml version="1.0"?>-<catalog> -<book id="bk101"> <author>Gambardella, Matthew</author> <title>XML Developer‘s Guide</title> <genre>Computer</genre> <price>44.95</price> <publish_date>2000-10-01</publish_date> <description>An in-depth look at creating applications with XML.</description> </book> +<book id="bk102"> -<book id="bk103"> <author>Corets, Eva</author> <title>Maeve Ascendant</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2000-11-17</publish_date> <description>After the collapse of a nanotechnology society in England, the young survivors lay the foundation for a new society.</description> </book> -<book id="bk104"> <author>Corets, Eva</author> <title>Oberon‘s Legacy</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2001-03-10</publish_date> <description>In post-apocalypse England, the mysterious agent known only as Oberon helps to create a new life for the inhabitants of London. Sequel to Maeve Ascendant.</description> </book> -<book id="bk105"> <author>Corets, Eva</author> <title>The Sundered Grail</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2001-09-10</publish_date> <description>The two daughters of Maeve, half-sisters, battle one another for control of England. Sequel to Oberon‘s Legacy.</description> </book> -<book id="bk106"> <author>Randall, Cynthia</author> <title>Lover Birds</title> <genre>Romance</genre> <price>4.95</price> <publish_date>2000-09-02</publish_date> <description>When Carla meets Paul at an ornithology conference, tempers fly as feathers get ruffled.</description> </book> -<book id="bk107"> <author>Thurman, Paula</author> <title>Splish Splash</title> <genre>Romance</genre> <price>4.95</price> <publish_date>2000-11-02</publish_date> <description>A deep sea diver finds true love twenty thousand leagues beneath the sea.</description> </book> -<book id="bk108"> <author>Knorr, Stefan</author> <title>Creepy Crawlies</title> <genre>Horror</genre> <price>4.95</price> <publish_date>2000-12-06</publish_date> <description>An anthology of horror stories about roaches, centipedes, scorpions and other insects.</description> </book> -<book id="bk109"> <author>Kress, Peter</author> <title>Paradox Lost</title> <genre>Science Fiction</genre> <price>6.95</price> <publish_date>2000-11-02</publish_date> <description>After an inadvertant trip through a Heisenberg Uncertainty Device, James Salway discovers the problems of being quantum.</description> </book> -<book id="bk110"> <author>O‘Brien, Tim</author> <title>Microsoft .NET: The Programming Bible</title> <genre>Computer</genre> <price>36.95</price> <publish_date>2000-12-09</publish_date> <description>Microsoft‘s .NET initiative is explored in detail in this deep programmer‘s reference.</description> </book> -<book id="bk111"> <author>O‘Brien, Tim</author> <title>MSXML3: A Comprehensive Guide</title> <genre>Computer</genre> <price>36.95</price> <publish_date>2000-12-01</publish_date> <description>The Microsoft MSXML3 parser is covered in detail, with attention to XML DOM interfaces, XSLT processing, SAX and more.</description> </book> -<book id="bk112"> <author>Galos, Mike</author> <title>Visual Studio 7: A Comprehensive Guide</title> <genre>Computer</genre> <price>49.95</price> <publish_date>2001-04-16</publish_date> <description>Microsoft Visual Studio 7 is explored in depth, looking at how Visual Basic, Visual C++, C#, and ASP+ are integrated into a comprehensive development environment.</description> </book> </catalog>

  嗯,貌似看起來有些亂,不過馬上我們處理了之後,它就會變得整齊。接下來在後台我們開始操作XML,首先我們需要讓GridView顯示資料:首先我們需要建立一個資料集DataSet,然後使用ADO.NET中內建的方法去讀取XML,這裡的實現很簡單:

  

 DataSet ds = new DataSet();  string Path = Server.MapPath("XML/books.xml"); ds.ReadXml(Path);

  這樣我們的ds中就已經有資料了,接下來綁定GridView後,呈現出來的就是這樣:

  

  這時候我們的XML已經讀取成功了,接下來我們可以簡單的操作下XML中的節點:

  

       private void ShowXML(string Path)         {              XmlDocument doc = new XmlDocument();            doc.Load(Path);            XmlNodeList nodeList = doc.SelectNodes("//title");            foreach(XmlNode node in nodeList)                        {                txtShow.Text += node.InnerXml + "\r\n";            }        }        protected void btnExport_Click(object sender, EventArgs e)        {            string Path = Server.MapPath("XML/books.xml");            ShowXML(Path);        }

   這裡我們用到了XmlDocument類,這個類是用於表示整個XML的DOM,另外一個XmlNode類是表示XML中的一個節點,而XmlNodeList則是表示可以迭代的,XmlNode的一個集合,我們在這裡是在載入了DOM對象後,選擇了title節點的集合,然後遍曆出每個節點下的內容並賦值給txtShow,效果如下:

  

  至此我們已經成功讀取到該節點,關於XML的簡單操作就介紹到這裡。XML的其他動作還有XmlPath的方式,以及各種其他複雜的方式。不過對於XML本身,可以理解為一個DOM,也就是一種特殊的HTML,它擁有自己的標記格式,拋磚引玉,希望大家提出批評和建議。

  ---------------------------------------------------分割線-----------------------------------------------------------

  之前因為手誤的原因,在本地的方法中加入了ds這個參數,後來發現文中完全沒有用到這個參數,感謝@佩恩六道的指正,原文已經修改。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.