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

  如题,我们保存数据的方式有很多种。在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这个参数,后来发现文中完全没有用到这个参数,感谢@佩恩六道的指正,原文已经修改。

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

时间: 2024-08-08 03:50:45

ADO.NET系列之操作XML(一)的相关文章

C#对各种文件的操作-xml(3)

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Xml.Linq; 7 using System.Xml; 8 using System.Xml.Serialization; 9 using System.IO; 10 11 namespace XMLFileOpe

DOM系列---DOM操作样式

发文不易,若转载传播,请亲注明出处,谢谢! 一.操作样式 CSS作为(X)HTML的辅助,可以增强页面的显示效果.但不是每个浏览器都能支持最新的CSS能力.CSS的能力和DOM级别密切相关,所以我们有必要检测当前浏览器支持CSS能力的级别. DOM1级实现了最基本的文档处理,DOM2和DOM3在这个基础上增加了更多的交互能力,这里我们主要探讨CSS,DOM2增加了CSS编程访问方式和改变CSS样式信息. DOM一致性检测 功能 版本号 说明 Core 1.0.2.0.3.0 基本的DOM,用于表

C#操作XML文档总结

包括XMLWriter写入,XmlReader读取,XmlDocument操作,DataSet.ReadXML(),DataSet.WriteXML(),LINQ查询XML 1.XMLWriter写入XML数据 结果会覆盖原文档. c#_code: //使用XMLWriter写XML数据 XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; //缩进 //settings.NewLineOnAt

php操作xml小结

<?php #php操作xml,SimpleXMLElement类小结 header('Content-type:text/html;charset=utf-8;'); //1.构造函数 /* $xmlstring=<<<XML <?xml version="1.0" encoding="utf-8"?> <note  xmlns:b="http://www.w3school.com.cn/example/&quo

使用Dom4j操作XML数据

--------------siwuxie095 dom4j 是一个非常优秀的 Java XML 的 API, 用来读写 XML 文件 和操作 XML 数据 特点:性能优异.功能强大.极端易用 dom4j 的下载链接:http://www.dom4j.org/dom4j-1.6.1/ 将 dom4j-1.6.1.zip 解压一览: 工程名:TestDom4j 包名:com.siwuxie095.dom4j 类名:Test.java 打开资源管理器,在工程 TestDom4j 文件夹下,创建一个

dom4j操作xml对象

// 获取Documen对象 public static Document getDocument(String path) throws Exception{ // 解析器对象 SAXReader reader = new SAXReader(); // 解析 return reader.read(path); } // 回写(XMLWriter) public static void writeXml(Document document,String path) throws Excepti

转载:用Ant操作XML文件

1.14 用XMLTask操作XML(1) 本节作者:Brian Agnew 对于简单的文本搜索和替换操作,Ant的<replace>任务就够用了,但在现代Java框架中,用户更可能需要强大的XML操作能力来修改servlet描述符.Spring配置等. XMLTask是Ant外部任务,它提供了强大的XML编辑工具,主要用于在构建/部署过程中创建和修改XML文件. 使用XMLTask的好处如下? 与Ant的<replace>任务不同,XMLTask使用XPath提供识别XML文档各

简单操作XML

第一部分 什么是XML? XML, Extensible Markup Language ,可扩展标记语言,主要用途是描述和交换数据.它的一个用处是配置文件,用来保存数据库连接字符串.端口.IP.日志保存路径等参数.我们可以使用文本文件来保存文件,使用 key = value, key2 = value2 ,...... 的方式来保存数据.这样做的坏处是结构比较不规矩,读取起来也不方便,需要自行编写一长串的if / else 语句.为了解决这些问题,我们可以使用XML. XML定义了一组规则,即

C#操作XML增删改查

XML文件是一种常用的文件格式,不管是B/S还是C/S都随处可见XML的身影.Xml是Internet环境中跨平台的,依赖于内容的技术,是当前处理结构化文档信息的有力工具.XML是一种简单的数据存储语言,使用一系列简单的标记描述数据,而这些标记可以用方便的方式建立,虽然XML占用的空间比二进制数据要占用更多的空间,但XML极其简单易于掌握和使用.微软也提供了一系列类库来倒帮助我们在应用程序中存储XML文件. “在程序中访问进而操作XML文件一般有两种模型,分别是使用DOM(文档对象模型)和流模型