c操作xml的完整例子

  • 格式:pdf
  • 大小:49.67 KB
  • 文档页数:4
这是一个用 c# 控制台程序下, 用 XmlDocument 进行 XML 操作的的例子,包含了查询、
增加、修改、删除、保存的基本操作。较完整的描述了一个
XML 的整个操作流程。适合刚
入门 .net XML 操作的朋友参考和学习。
假设有 XML 文件: books.xml
<? xml version="1.0" encoding="UTF-8" ?> <books > <book >
//--- 再将所有价格低于 10 的书删除 ----
XmlNodeList someBooks = root.SelectNodes("/books/bo
ok[price<10]");
Console.Out.WriteLine("---
再将所有价格低于 10 的书
删除 ---");
Console.Out.WriteLine("--eBooks.Count + " 本。 ---");
新书更好看。 ";
theBook.AppendChild(theElem);root.Appen来自Child(theBook);
Console.Out.WriteLine("---
新建一本书开始 ----");
Console.Out.WriteLine(root.OuterXml);
//--- 新建一本书完成 ----
//--- 对《哈里波特》修改完成。 ----
//---
再将所有价格低于 10 的书删除 ----
theBook = (XmlElement)root.SelectSingleNode("/books
/book[@id='B02']");
Console.Out.WriteLine("---
要用 id 属性删除《三国演
下面是为 Program.cs
using System; using System.Collections.Generic;
using System.Text; using System.Xml;
namespaceTestXml
{
class Program
{
static void Main( string [] args)
theElem = xmldoc.CreateElement("price"); theElem.InnerText = "20"; theBook.AppendChild(theElem);
theElem = xmldoc.CreateElement("memo");
theElem.InnerText = "
Console.Out.WriteLine(theBook.OuterXml);
//--- 此时修改这本书的价格 -----
theBook.GetElementsByTagName("price").Item(0).Inner
Text = "15"; //getElementsByTagName 返回的是 NodeList ,所以要跟上 item
义》这本书 ----");
Console.Out.WriteLine(theBook.OuterXml);
theBook.ParentNode.RemoveChild(theBook);
Console.Out.WriteLine("---
删除后的XML ----");
Console.Out.WriteLine(xmldoc.OuterXml);
(0) 。另外, GetElementsByTagName("price") 相当于 SelectNodes(".//price
") 。
Console.Out.WriteLine("---
此时修改这本书的价格 --
--");
Console.Out.WriteLine(theBook.OuterXml);
//---
下面对《哈里波特》做一些修改。 ----
//---
查询找《哈里波特》 ----
theBook = (XmlElement)root.SelectSingleNode("/books
/book[name=' 哈里波特 ']");
Console.Out.WriteLine("---
查找《哈里波特》 ----");
<name >哈里波特 </name > <price >10 </price > <memo >这是一本很好看的书。 </memo > </ book > <book id ="B02"> <name >三国演义 </name > <price >10 </price > <memo >四大名著之一。 </ memo > </ book > <book id ="B03"> <name >水浒 </ name > <price >6</ price > <memo >四大名著之一。 </ memo > </ book > <book id ="B04"> <name >红楼 </ name > <price >5</ price > <memo >四大名著之一。 </ memo > </ book > </books >
//--- 另外还想加一个属性 id ,值为 B01 ----
theBook.SetAttribute("id", "B01");
Console.Out.WriteLine("---
另外还想加一个属性 id ,
值为 B01 ----");
Console.Out.WriteLine(theBook.OuterXml);
{
XmlElement theBook =
null , theElem = null , root =
XmlDocument xmldoc =
new XmlDocument();
try
{
xmldoc.Load("Books.xml");
root = xmldoc.DocumentElement;
null ;
//--- 新建一本书开始 ----
theBook = xmldoc.CreateElement("book");
theElem = xmldoc.CreateElement("name");
theElem.InnerText = "
新书 ";
theBook.AppendChild(theElem);