对于XML的操作,首先借助于XMLHelper类,新增了两个,见Magic项目的vessel窗口。
写几个常用的用法:

C# Xml 移除指定节点

XML样例:



  
    Net从入门到精通
    李大蒜
    58.3
  
  
    CS从入门到精通
    候捷
    58.3
  
  
    CS从入门到精通
    候捷
    58.3
  

执行代码一

/// 
/// 删除属性值等于“AttributeValue”的节点
/// 
/// XML文档完全文件名(包含物理路径)
/// 要匹配的XPath表达式(例如:"//节点名//子节点名
/// 要删除包含xmlAttributeName属性的节点的名称
/// 
private void XmlNodeByXPath(string xmlFileName, string xpath, string xmlAttributeName, string AttributeValue)
{
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(xmlFileName);
    XmlNodeList xNodes = xmlDoc.SelectSingleNode(xpath).ChildNodes;
    for (int i = xNodes.Count - 1; i >= 0; i--)
    {
        XmlElement xe = (XmlElement)xNodes[i];
        if (xe.GetAttribute(xmlAttributeName) == AttributeValue)
        {
            xNodes[i].ParentNode.RemoveChild(xNodes[i]);
        }
    }
    xmlDoc.Save(xmlFileName);
}

实验:XmlNodeByXPath(“E:\bookstore.xml”, “bookstore”, “genre”, “李3”);
结果:



  
    Net从入门到精通
    李大蒜
    58.3
  
  
    CS从入门到精通
    候捷
    58.3
  

小注:
1、删除节点不能使用foreach,使用的话会造成删除XML一个节点,就跳出循环,也不报错,很隐蔽的错误。
2、该函数也可以这么实现

/// 
/// 删除属性值等于“AttributeValue”的节点
/// 
/// XML文档完全文件名(包含物理路径)
/// 要匹配的XPath表达式(例如:"//节点名//子节点名
/// 要删除包含xmlAttributeName属性的节点的名称
/// 
private void XmlNodeByXPath(string xmlFileName, string xpath, string xmlAttributeName, string AttributeValue)
{
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(xmlFileName);
    XmlNode root = xmlDoc.SelectSingleNode(xpath);
    XmlNodeList xnl = xmlDoc.SelectSingleNode(xpath).ChildNodes;
    for (int i = 0; i < xnl.Count; i++)
    {
        XmlElement xe = (XmlElement)xnl.Item(i);
        if (xe.GetAttribute(xmlAttributeName) == AttributeValue)
        {
            root.RemoveChild(xe);
            if (i < xnl.Count) i = i - 1;
        }
    }
    xmlDoc.Save(xmlFileName);   
}

C#操作XML方法:新增、修改和删除节点与属性

一 前言

先来了解下操作XML所涉及到的几个类及之间的关系 如果大家发现少写了一些常用的方法,麻烦在评论中指出,我一定会补上的!谢谢大家

  • 1 XMLElement 主要是针对节点的一些属性进行操作
  • 2 XMLDocument 主要是针对节点的CUID操作
  • 3 XMLNode 为抽象类,做为以上两类的基类,提供一些操作节点的方法
    XML结构

清楚了以上的关系在操作XML时会更清晰一点
二 具体操作

以下会对Xml的结点与属性做增 删 改 查的操作也满足了实际工作中的大部分情况

先构造一棵XML树如下,其中也涉及到了写入xml文档的操作

public void CreatXmlTree(string xmlPath)
 {
     XElement xElement = new XElement(
         new XElement("BookStore",
             new XElement("Book",
                 new XElement("Name", "C#入门", new XAttribute("BookName", "C#")),
                 new XElement("Author", "Martin", new XAttribute("Name", "Martin")),
                 new XElement("Adress", "上海"),
                 new XElement("Date", DateTime.Now.ToString("yyyy-MM-dd"))
                 ),
             new XElement("Book",
                 new XElement("Name", "WCF入门", new XAttribute("BookName", "WCF")),
                 new XElement("Author", "Mary", new XAttribute("Name", "Mary")),
                 new XElement("Adress", "北京"),
                 new XElement("Date", DateTime.Now.ToString("yyyy-MM-dd"))
                 )
                 )
         );

     //需要指定编码格式,否则在读取时会抛:根级别上的数据无效。 第 1 行 位置 1异常
     XmlWriterSettings settings = new XmlWriterSettings();
     settings.Encoding = new UTF8Encoding(false);
     settings.Indent = true;
     XmlWriter xw = XmlWriter.Create(xmlPath,settings);
     xElement.Save(xw);
     //写入文件
     xw.Flush();
     xw.Close();
 }

然后得到如下的XML树

 
 
     
         C#入门
         Martin
         2013-10-11
         上海
         2013-10-11
     
     
         WCF入门
         Mary
         北京
         2013-10-11
     
 

以下操作都是对生成的XML树进行操作
2.1 新增节点与属性

新增节点NewBook并增加属性Name=”WPF”

 public void Create(string xmlPath)
 {
     XmlDocument xmlDoc = new XmlDocument();
     xmlDoc.Load(xmlPath);
     
     var root = xmlDoc.DocumentElement;//取到根结点
     XmlNode newNode = xmlDoc.CreateNode("element", "NewBook", "");
     newNode.InnerText = "WPF";

     //添加为根元素的第一层子结点
     root.AppendChild(newNode);
     xmlDoc.Save(xmlPath);
 }

开篇有写操作xml节点属性主要用XmlElement对象所以取到结点后要转类型

 //属性
 public void CreateAttribute(string xmlPath)
 {
     XmlDocument xmlDoc = new XmlDocument();
     xmlDoc.Load(xmlPath);
     var root = xmlDoc.DocumentElement;//取到根结点
     XmlElement node = (XmlElement)xmlDoc.SelectSingleNode("BookStore/NewBook");
     node.SetAttribute("Name", "WPF");
     xmlDoc.Save(xmlPath);

 }

效果如下
02.png
2.2 删除节点与属性

 public void Delete(string xmlPath)
 {
     XmlDocument xmlDoc = new XmlDocument();
     xmlDoc.Load(xmlPath);
     var root = xmlDoc.DocumentElement;//取到根结点

     var element = xmlDoc.SelectSingleNode("BookStore/NewBook");
     root.RemoveChild(element);
     xmlDoc.Save(xmlPath);
 }

删除属性

 public void DeleteAttribute(string xmlPath)
 {
     XmlDocument xmlDoc = new XmlDocument();
     xmlDoc.Load(xmlPath);
     XmlElement node = (XmlElement)xmlDoc.SelectSingleNode("BookStore/NewBook");
     //移除指定属性
     node.RemoveAttribute("Name");
     //移除当前节点所有属性,不包括默认属性
     //node.RemoveAllAttributes();
     xmlDoc.Save(xmlPath);
 }

2.3 修改节点与属性

xml的节点默认是不允许修改的,本文也就不做处理了

修改属性代码如下

 public void ModifyAttribute(string xmlPath)
 {
     XmlDocument xmlDoc = new XmlDocument();
     xmlDoc.Load(xmlPath);
     XmlElement element = (XmlElement)xmlDoc.SelectSingleNode("BookStore/NewBook");
     element.SetAttribute("Name", "Zhang");
     xmlDoc.Save(xmlPath);
 }

效果如下
03.png

2.4 获取节点与属性

 public void Select(string xmlPath)
 {
     XmlDocument xmlDoc = new XmlDocument();
     xmlDoc.Load(xmlPath);
     //取根结点
     var root = xmlDoc.DocumentElement;//取到根结点
     //取指定的单个结点
     XmlNode oldChild = xmlDoc.SelectSingleNode("BookStore/NewBook");
     
     //取指定的结点的集合
     XmlNodeList nodes = xmlDoc.SelectNodes("BookStore/NewBook");

     //取到所有的xml结点
     XmlNodeList nodelist = xmlDoc.GetElementsByTagName("*");
 }

属性

 public void SelectAttribute(string xmlPath)
 {
     XmlDocument xmlDoc = new XmlDocument();
     xmlDoc.Load(xmlPath);
     XmlElement element = (XmlElement)xmlDoc.SelectSingleNode("BookStore/NewBook");
     string name = element.GetAttribute("Name");
     Console.WriteLine(name);
 }

三 linq to XML 操作
不提了,用到了再搜索吧。