当前位置:首页 >.NET > 正文内容

C#读写XML

大滑稽11年前 (2014-03-24).NET1253

已知有一个XML文件(bookstore.xml)如下:
<?xml version="1.0" encoding="gb2312"?>
<bookstore>
  <book genre="fantasy" ISBN="2-3631-4">
    <title>Oberon's 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>Oberon's 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>Oberon's 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>Oberon's 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);//显示子节点点文本
    }
   }
 

 

 


Linq TO  SQL

 
1、LINQ to XML类
 
 
 


 
 
以下的代码演示了如何使用LINQ to XML来快速创建一个xml:
 

隐藏行号 复制代码 ? 创建 XML
 
1.public static void CreateDocument()
 
2.{
 
3.    string path = @"d:\website";
 
4.
 5.    XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
 
6.                                   new XElement("Root", "root"));
 
7.
 8.    xdoc.Save(path);
 
9.}
 

运行该示例将会得到一个xml文件,其内容为:
 
<?xml version="1.0" encoding="utf-8" standalone="yes"?> <Root>root</Root>
 
 
2、XElement类
 
XElement 类是 LINQ to XML 中的基础类之一。 它表示一个 XML 元素。 可以使用该类创建元素;更改元素内容;添加、更改或删除子元素;向元素中添加属性;或以文本格式序列化元素内容。 还可以与 System.Xml 中的其他类(例如 XmlReader、XmlWriter 和 XslCompiledTransform)进行互操作。
 
使用LINQ to XML创建xml文档有很多种方式,具体使用哪种方法要根据实际需要。而创建xml文档最简单、最常见的方式是使用XElement类。以下的代码演示了如何使用XElement类创建一个xml文档:
 
 
 

显示行号 复制代码 ? 这是一段程序代码。
 
1.public static void CreateCategories()
 
2.{
 
3.    string path = @"d:\website";
 
4.
 5.    XElement root = new XElement("Categories",
 
6.
 7.        new XElement("Category",
 
8.
 9.            new XElement("CategoryID", Guid.NewGuid()),
 
10.
 11.            new XElement("CategoryName", "Beverages")
 
12.            ),
 
13.
 14.        new XElement("Category",
 
15.
 16.            new XElement("CategoryID", Guid.NewGuid()),
 
17.
 18.            new XElement("CategoryName", "Condiments")
 
19.
 20.            ),
 
21.
 22.        new XElement("Category",
 
23.
 24.            new XElement("CategoryID", Guid.NewGuid()),
 
25.
 26.            new XElement("CategoryName", "Confections")
 
27.
 28.            )
 
29.
 30.       );
 
31.
 32.    root.Save(path);
 
33.
 34.}
 

运行该示例将会得到一个xml文件,其内容为:
 
<?xml version="1.0" encoding="utf-8"?> <Categories>   <Category>     <CategoryID>57485174-46fc-4e8c-8d98-d25b53d504a1</CategoryID>     <CategoryName>Beverages</CategoryName>   </Category>   <Category>     <CategoryID>1474dde1-8014-48f7-b093-b47ca5d5b770</CategoryID>     <CategoryName>Condiments</CategoryName>   </Category>   <Category>     <CategoryID>364224e0-e002-4939-90fc-0fd93e0cf35b</CategoryID>     <CategoryName>Confections</CategoryName>   </Category> </Categories>
 
 
XElement类包含了许多方法,这些方法使得处理xml变得轻而易举。有关这些方法请参照MSDN。
 
其中,Save、CreateReader、ToString和WriteTo方法是比较常用的三个方法:
 


 
 
3、XAttribute类
 
 
 
XAttribute类用来处理元素的属性,属性是与元素相关联的“名称-值”对,每个元素中不能有名称重复的属性。使用XAttribute类与使用XElement类的操作十分相似,下面的示例演示了如何在创建xml树时为其添加一个属性:
 

显示行号 复制代码 ? 这是一段程序代码。
 
1.public static XElement CreateCategoriesByXAttribute()
 
2.{
 
3.    XElement root = new XElement("Categories",
 
4.
 5.        new XElement("Category",
 
6.
 7.            new XAttribute("CategoryID", Guid.NewGuid()),
 
8.
 9.            new XElement("CategoryName", "Beverages")
 
10.
 11.            ),
 
12.
 13.        new XElement("Category",
 
14.
 15.            new XAttribute("CategoryID", Guid.NewGuid()),
 
16.
 17.            new XElement("CategoryName", "Condiments")
 
18.
 19.            ),
 
20.
 21.        new XElement("Category",
 
22.
 23.            new XAttribute("CategoryID", Guid.NewGuid()),
 
24.
 25.            new XElement("CategoryName", "Confections")
 
26.
 27.            )
 
28.       );
 
29.
 30.    root.Save(path);
 
31.
 32.    return root;
 
33.}
 

运行该示例将会得到一个xml文件,其内容为:
 
<?xml version="1.0" encoding="utf-8"?> <Categories>   <Category CategoryID="a6d5ef04-3f83-4e00-aeaf-52444add7570">     <CategoryName>Beverages</CategoryName>   </Category>   <Category CategoryID="67a168d5-6b22-4d82-9bd4-67bec88c2ccb">     <CategoryName>Condiments</CategoryName>   </Category>   <Category CategoryID="17398f4e-5ef1-48da-8a72-1c54371b8e76">     <CategoryName>Confections</CategoryName>   </Category> </Categories>
 
 
XAttribute类的方法比较少,常用的三个是:
 


 
 
以下的示例使用Remove来删除第一个元素的CategoryID属性:
 

显示行号 复制代码 ? 这是一段程序代码。
 
1.public static void RemoveAttribute()
 
2.{
 
3.
 4.    XElement xdoc = CreateCategoriesByXAttribute();
 
5.
 6.    XAttribute xattr = xdoc.Element("Category").Attribute("CategoryID");
 
7.
 8.    xattr.Remove();
 
9.
 10.    xdoc.Save(path);
 
11.
 12.}
 

运行该示例将会得到一个xml文件,其内容为:
 
<?xml version="1.0" encoding="utf-8"?> <Categories>   <Category>     <CategoryName>Beverages</CategoryName>   </Category>   <Category CategoryID="5c311c1e-ede5-41e5-93f7-5d8b1d7a0346">     <CategoryName>Condiments</CategoryName>   </Category>   <Category CategoryID="bfde8db5-df84-4415-b297-cd04d8db9712">     <CategoryName>Confections</CategoryName>   </Category> </Categories>
 
 
作为尝试,试一试以下删除属性的方法:
 

显示行号 复制代码 ? 这是一段程序代码。
 
1.public static void RemoveAttributeByDoc()
 
2.{
 
3.
 4.    XElement xdoc = CreateCategoriesByXAttribute();
 
5.
 6.    XAttribute xattr = xdoc.Attribute("CategoryID");
 
7.
 8.    xattr.Remove();
 
9.
 10.    xdoc.Save(path);
 
11.
 12.}
 

运行该示例将会抛出一个空引用异常,因为元素Categories没有一个叫做CategoryID的属性。
 
 
 
4、XDocument类
 
 
 
XDocument类提供了处理xml文档的方法,包括声明、注释和处理指令。一个XDocument对象可以包含以下内容:
 


下面的示例创建了一个简单的xml文档,它包含几个元素和一个属性,以及一个处理指令和一些注释:
 

显示行号 复制代码 ? 这是一段程序代码。
 
1.public static void CreateXDocument()
 
2.      {
 
3.
 4.          XDocument xdoc = new XDocument(
 
5.
 6.                  new XProcessingInstruction("xml-stylesheet", "title='EmpInfo'"),
 
7.
 8.                  new XComment("some comments"),
 
9.
 10.                  new XElement("Root",
 
11.
 12.                          new XElement("Employees",
 
13.
 14.                                  new XElement("Employee",
 
15.
 16.                                          new XAttribute("id", "1"),
 
17.
 18.                                          new XElement("Name", "Scott Klein"),
 
19.
 20.                                          new XElement("Title", "Geek"),
 
21.
 22.                                          new XElement("HireDate", "02/05/2007"),
 
23.
 24.                                          new XElement("Gender", "M")
 
25.
 26.                                      )
 
27.
 28.                              )
 
29.
 30.                      ),
 
31.
 32.                  new XComment("more comments")
 
33.
 34.              );
 
35.
 36.          xdoc.Save(path);
 
37.
 38.      }
 

运行该示例将会得到一个xml文件,其内容为:
 
<?xml version="1.0" encoding="utf-8"?> <?xml-stylesheet title='EmpInfo'?> <!--some comments--> <Root>   <Employees>     <Employee id="1">       <Name>Scott Klein</Name>       <Title>Geek</Title>       <HireDate>02/05/2007</HireDate>       <Gender>M</Gender>     </Employee>   </Employees> </Root> <!--more comments-->
 
 
XDocument类包含多个与XElement类相同的方法,具体内容可以参阅MSDN。需要注意的是,处理节点和元素的大部分功能都可以通过 XElement获得,只有当绝对需要文档层次的处理能力,以及需要访问注释、处理指令和声明时,才有使用XDocument类的必要。
 
 
 
创建了xml文档后,可以使用NodesAfterSelf方法返回指定的XElement元素之后的所有同级元素。需要注意的是,此方法只包括返回集合中的同级元素,而不包括子代。此方法使用延迟执行。以下代码演示了这一过程:
 

显示行号 复制代码 ? 这是一段程序代码。
 
1.public static void NodesAfterSelf()
 
2.{
 
3.
 4.    XElement root = new XElement("Categories",
 
5.        new XElement("Category",
 
6.                new XElement("CategoryID", Guid.NewGuid()),
 
7.                new XElement("CategoryName", "食品"),
 
8.                new XElement("Description", "可以吃的东西")
 
9.            )
 
10.        );
 
11.
 12.    foreach (var item in root.Element("Category").Element("CategoryID").NodesAfterSelf())
 
13.    {
 
14.        Console.WriteLine((item as XElement).Value);
 
15.    }
 
16.}
 

 
 
 
 
二、LINQ to XML编程概念
 
 
 
本节将介绍LINQ to XML编程的相关概念,例如如何加载xml、创建全新xml、操纵xml的信息以及遍历xml文档。
 
 
 
1、加载已有的xml
 
使用LINQ to XML加载xml可以从多种数据源获得,例如字符串、XmlReader、TextReader或文件。
 
下面的示例演示了如何从文件中加载xml:
 

显示行号 复制代码 ? 这是一段程序代码。
 
1.
 2.public static void LoadFromFile()
 
3.{
 
4.
 5.    XElement root = XElement.Load(path);
 
6.
 7.    Console.WriteLine(root.ToString());
 
8.
 9.}
 

也可以使用Parse方法从一个字符串加载xml:
 

显示行号 复制代码 ? 这是一段程序代码。
 
1.    public static void LoadFromString()
 
2.    {
 
3.
 4.        XElement root = XElement.Parse(@"
 
5.
 
6.    <Categories>
 
7.
 
8.      <Category>
 
9.
 
10.        <CategoryID>1</CategoryID>
 
11.
 
12.        <CategoryName>Beverages</CategoryName>
 
13.
 
14.        <Description>Soft drinks, coffees, teas, beers, and ales</Description>
 
15.
 
16.      </Category>
 
17.
 
18.    </Categories>
 
19.
 
20.");
 
21.
 22.        Console.WriteLine(root.ToString());
 
23.
 24.    }
 

 
 
2、保存xml
 
在前面的示例中曾多次调用XElement对象的Save方法来保存xml文档,在这里就不冗述了。
 
 
 
3、创建xml
 
在前面的示例中曾多次调用XElement对象的构造函数来创建xml文档,在这里就不冗述了。需要说明的是,在使用LINQ to XML创建xml文档时,会有代码缩进,这使代码的可读性大大加强。
 
 
 
4、遍历xml
 
使用LINQ to XML在xml树中遍历xml是相当简单的。只需要使用XElement和XAttribute类中所提供的方法。Elements和Element方法提供了定位到某个或某些元素的方式。下面的示例演示了如何遍历xml树,并获取指定元素的方式:
 

显示行号 复制代码 ? 这是一段程序代码。
 
1.public static void Enum()
 
2.
 3.{
 
4.
 5.    XElement root = new XElement("Categories");
 
6.
 7.    using (NorthwindDataContext db = new NorthwindDataContext())
 
8.
 9.    {
 
10.
 11.        root.Add(
 
12.
 13.                db.Categories
 
14.
 15.                .Select
 
16.
 17.                (
 
18.
 19.                    c => new XElement
 
20.
 
21.                    (
 
22.
 23.                        "Category"
 
24.
 
25.                        , new XElement("CategoryName", c.CategoryName)
 
26.
 27.                    )
 
28.
 29.                )
 
30.
 31.            );
 
32.
 33.    }
 
34.
 35.    foreach (var item in root.Elements("Category"))
 
36.    {
 
37.        Console.WriteLine(item.Element("CategoryName").Value);
 
38.
 39.    }
 
40.
 41.}
 

上述代码运行的结果为:
 
 
 
是不是很简单呢?Nodes()、Elements()、Element(name)和Elements(name)方法为xml树的导航提供了基本功能。
 
 
 
5、操纵xml
 
LINQ to XML一个重要的特性是能够方便地修改xml树,如添加、删除、更新和复制xml文档的内容。
 
I.插入
 
使用XNode类的插入方法可以方便地向xml树添加内容:
 


在下面的示例中,使用AddAfterSelf方法向现有xml中添加一个新节点:
 

显示行号 复制代码 ? 这是一段程序代码。
 
1.public static void AddAfterSelf()
 
2.
 3.{
 
4.
 5.    XElement root = XElement.Parse(@"
 
6.
 
7.        <Categories>
 
8.
 
9.          <Category>
 
10.
 
11.            <CategoryID>1</CategoryID>
 
12.
 
13.            <CategoryName>Beverages</CategoryName>
 
14.
 
15.            <Description>Soft drinks, coffees, teas, beers, and ales</Description>
 
16.
 
17.          </Category>
 
18.
 
19.        </Categories>
 
20.
 
21.    ");
 
22.
 23.    XElement xele = root.Element("Category").Element("CategoryName");
 
24.
 25.    xele.AddAfterSelf(new XElement("AddDate", DateTime.Now));
 
26.
 27.    root.Save(path);
 
28.
 29.}
 

运行该示例将会得到一个xml文件,其内容为:
 
<?xml version="1.0" encoding="utf-8"?> <Categories>   <Category>     <CategoryID>1</CategoryID>     <CategoryName>Beverages</CategoryName>     <AddDate>2010-01-31T03:08:51.813736+08:00</AddDate>     <Description>Soft drinks, coffees, teas, beers, and ales</Description>   </Category> </Categories>
当需要添加一个元素到指定节点之前时,可以使用AddBeforeSelf方法。
 
 
 
II.更新
 
在LINQ to XML中更新xml内容可以使用以下几种方法:
 


在下面的示例中使用了ReplaceWith与SetElementValue方法对xml进行了更新操作:
 

显示行号 复制代码 ? 这是一段程序代码。
 
1.public static void Update()
 
2.{
 
3.
 4.    XElement root = XElement.Parse(@"
 
5.                                   <Categories>
 
6.                                      <Category>
 
7.                                        <CategoryID>1</CategoryID>
 
8.                                        <CategoryName>Beverages</CategoryName>
 
9.                                        <Description>Soft drinks, coffees, teas, beers, and ales</Description>
 
10.                                      </Category>
 
11.                                    </Categories>
 
12.                                  ");
 
13.
&

扫描二维码推送至手机访问。

版权声明:本文由第★一★次发布,如需转载请注明出处。

本文链接:http://wpers.net/post/41.html

标签:C#.NETXML

“C#读写XML” 的相关文章

Cbo控件数据源绑定

 //Cbo控件数据源绑定DataTable DtType = noteType.GetTypeList("");         ...

C#遍历控件的方法

首先,要想遍历,就必须找到你想找的表单里面的所有控件,然后一个个的逐一比对,当找到了你需要的控件的时候,再做你需要的操作。1、foreach方法foreach (Control control in ...

Linq读写XML

         private List<News> GetNews(string html)    &n...

修改注册表限制软件使用次数

 private void Form1_Load(object sender, System.EventArgs e){RegistryKey RootKey,RegKey; //项名为:HKEY_CURRENT_USER\So...

c#中分页显示数据

     //c#中分页显示数据    public partial class Form1 : Form    {  ...

C#修改浏览器主页

string key = @"HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main";      &n...