XML读、查、删

上面我们学习了用XmlTextWriter对象创建一个XML文档,在本节里,将继续介绍如何在已有XML文档中查询和插入节点。下面示例在book.xml根节点下加入新的<Book>节点:


XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("book.xml");
//查找<Books>
XmlNode root = xmlDoc.SelectSingleNode("Books");
//创建一个<Book>节点
XmlElement el = xmlDoc.CreateElement("Book");
//设置<Book>节点的属性BookName
el.SetAttribute("BookName", "Windows Application");
//创建<Book>节点的第一个下级节点
XmlElement elSubAuthor = xmlDoc.CreateElement("Author");
elSubAuthor.InnerText = "Jack";
el.AppendChild(elSubAuthor);
//创建<Book>节点的第二个下级节点
XmlElement elSubPrice = xmlDoc.CreateElement("Price");
elSubPrice.InnerText = "70.00";
el.AppendChild(elSubPrice);
//添加<Book>节点到<Books>中
root.AppendChild(el);
xmlDoc.Save("book.xml");
运行代码后,book.xml代码如下,加粗部分是新增的代码:
<?xml version="1.0"?>
<Books>
  <Book BookName=".NET框架">
    <Author>Jim</Author>
    <Price>40.00</Price>
  </Book>
  <Book BookName="C#">
    <Author>Tom</Author>
    <Price>60.00</Price>
  </Book>
  <Book BookName="ASP.NET">
    <Author>David</Author>
    <Price>100.00</Price>
  </Book>
  <Book BookName="Windows Application">
    <Author>Jack</Author>
    <Price>70.00</Price>
  </Book>
</Books>
下面示例演示了如何修改XML节点:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("book.xml");
XmlNodeList nodeList = xmlDoc.SelectSingleNode("Books").ChildNodes;
foreach (var node in nodeList)
{
    XmlElement el = (XmlElement)node;
    if (el.GetAttribute("BookName") == "C#")
    {
        el.SetAttribute("BookName", "精通C#");
    }
}
xmlDoc.Save("book.xml");
如果要输出book.xml文档中所有节点的属性和值,可以尝试在上例foreach中实现。
运行后,book.xml的代码如下,原来的“C#”被更改为了“精通C#”。
<?xml version="1.0"?>
<Books>
  <Book BookName=".NET框架">
    <Author>Jim</Author>
    <Price>40.00</Price>
  </Book>
  <Book BookName="精通C#">
    <Author>Tom</Author>
    <Price>60.00</Price>
  </Book>
  <Book BookName="ASP.NET">
    <Author>David</Author>
    <Price>100.00</Price>
  </Book>
  <Book BookName="Windows Application">
    <Author>Jack</Author>
    <Price>70.00</Price>
  </Book>
</Books>
如果要删除节点属性请使用RemoveAttribute方法,如果要删除节点请使用RemoveChild方法,也可以使用RemoveAll方法删除所有节点。关于这类方法的使用不再赘述。


另外DataSet也可以读写XML文件:
DataSet ds = new DataSet();
//方法有重载
ds.ReadXml(Server.MapPath("txt.xml"));
//方法有重载
ds.WriteXml(Server.MapPath("txt.xml"));
将字符串保存为XML文件
XmlDocument doc = new XmlDocument();  
doc.LoadXml(txtXMLEditor.Text);
doc.Save(Server.MapPath("XMLFile.xml")); 


C#创建XML文档、增删节点类:
复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
namespace OperateXml
{
    public class XmlHelper
    {
        /// <summary>
        /// 创建XML文件
        /// </summary>
        /// <param name="fileName">XML文件路径和文件名</param>
        /// <param name="rootElement">XML文件根元素名称</param>
        public static void CreateXmlFile(string fileName,string rootElement)
        {
            if (!File.Exists(fileName))
            {
                //创建Xml文件
                XmlTextWriter writer = new XmlTextWriter(fileName, Encoding.UTF8);
                //设置自动缩进
                writer.Formatting = Formatting.Indented;
                //XML版本声明
                writer.WriteStartDocument();
                //根元素
                writer.WriteStartElement(rootElement);
                //关闭根元素,并书写结束标签
                writer.WriteEndElement();
                //将XML写入文件并且关闭XmlTextWriter实例对象
                writer.Close();
            }
        }


        /// <summary>
        /// 添加XML数据
        /// </summary>
        /// <param name="fileName">XML文件路径和文件名</param>
        /// <param name="rootElement">XML文件根元素名称</param>
        /// <param name="itemElement">XML文件二级元素名称</param>
        /// <param name="childElement">XML文件三级元素名称和值</param>
        public static void AppendChildElement(string fileName, string rootElement,string itemElement, Dictionary<string,string> childElement)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(fileName);
            XmlNode root = xmlDoc.SelectSingleNode(rootElement);
            XmlElement el = xmlDoc.CreateElement(itemElement);
            foreach(var item in childElement)
            {
                XmlElement elChild = xmlDoc.CreateElement(item.Key);
                elChild.InnerText = item.Value;
                el.AppendChild(elChild);
            }


            root.AppendChild(el);
            xmlDoc.Save(fileName);
        }
        /// <summary>
        /// 删除数据行
        /// </summary>
        /// <param name="fileName">XML文件</param>
        /// <param name="rowNode">顶级节点</param>
        /// <param name="elementID">要查找的三级节点的InnerText,根据此值删除二级节点(一条数据)</param>
        public static void RemoveRecord(string fileName,string rowNode,string elementID)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(fileName);
            XmlNodeList nodeList = xmlDoc.SelectSingleNode(rowNode).ChildNodes;
            foreach (XmlNode node in nodeList)
            {
                XmlElement el = (XmlElement)node;
                XmlNodeList nodeListChild = el.ChildNodes;
                foreach (XmlNode nodeChild in nodeListChild)
                {
                    if (nodeChild.InnerText == elementID)
                    {
                        xmlDoc.SelectSingleNode(rowNode).RemoveChild(node);
                        break;
                    }
                }
            }
            xmlDoc.Save((fileName));
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值