C#修改XML的简单例子

接上一篇《C#写XML的简单例子》

 

这个例子要修改XML文件中结点的属性和和元素的文本

 

1 原xml文件 bookstore.xml

<?xml version="1.0" encoding="gb2312"?>
<bookstore>
  <book genre="love" ISBN="1234123">
    <title>who am i </title>
    <author>who</author>
    <price>999</price>
  </book>
  <book leixing="music" ISBN="56756">
    <title>CS从入门到精通</title>
    <author>候捷</author>
    <price>222</price>
  </book>
</bookstore>

 

2 program.cs

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            //实例化一个XmlDocument对象
            XmlDocument xmlDoc = new XmlDocument();
            //实例对象读取要写入的XML文件
            xmlDoc.Load("bookstore.xml");
            //获取bookstore节点的所有子节点
            XmlNodeList nodeList = xmlDoc.SelectSingleNode("bookstore").ChildNodes;
            //遍历所有子节点
            foreach (XmlNode xn in nodeList)
            {
                //将子节点类型转换为XmlElement类型
                XmlElement xe = (XmlElement)xn;
                //如果leixing属性值为“music”
                if (xe.GetAttribute("leixing") == "music")
                {
                    //则修改该属性为“love”
                    xe.SetAttribute("leixing", "love");
                    //继续获取xe子节点的所有子节点
                    XmlNodeList nls = xe.ChildNodes;
                    //遍历
                    foreach (XmlNode xn1 in nls)
                    {
                        //转换类型
                        XmlElement xe2 = (XmlElement)xn1;
                        //如果找到
                        if (xe2.Name == "author")
                        {
                            //则修改
                            xe2.InnerText = "黎明";
                            //找到退出来就可以了
                            break;
                        }
                    }
                    break;
                }
            }
           
            xmlDoc.Save("bookstore.xml");
        }
    }
}
3 修改后的结果如下:

<?xml version="1.0" encoding="gb2312"?>
<bookstore>
  <book genre="love" ISBN="1234123">
    <title>who am i </title>
    <author>who</author>
    <price>999</price>
  </book>
  <book leixing="love" ISBN="56756">
    <title>CS从入门到精通</title>
    <author>黎明</author>
    <price>222</price>
  </book>
</bookstore>

你可能感兴趣的:(C#修改XML的简单例子)