C# 操纵xml

对xml中的一些属性的理解:
1.innertext: 如果是root的话,会把所有的子节点的innertext的值连接在一起。
2.innerxml: 如果是root的话,会是所有根节点下面的所有的节点的信息,不包含根节点。
3.outxml:如果是root的话,会是根节点及其根节点下面所有节点的信息,包含根节点。
4.xmlDoucument意味着xml本身。

增加修改及删除
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
 
namespace XMLOperation
{
    class Program
    {
        static void Main(string[] args)
        {
            //xmldocument 和xmlElement 和XmlAttribute 都是继承或者间接继承XmlNode的。xmlNode是一个抽象类
            XmlDocument xmldoucment = new XmlDocument();//定义xml文档。
            xmldoucment.Load("books.xml");//加载xml,可以是绝对路径
 
            XmlElement root = xmldoucment.DocumentElement;//根
 
            //add element
            XmlElement addElement = xmldoucment.CreateElement("book");
            //add attribute
            XmlAttribute addAttribute = xmldoucment.CreateAttribute("id");
            addAttribute.Value = "B04";
            addElement.Attributes.Append(addAttribute);
 
            XmlElement nameElement = xmldoucment.CreateElement("name");
            nameElement.InnerText = "三国演义";
 
            XmlElement priElement = xmldoucment.CreateElement("price");
            priElement.InnerText = "60";
 
            XmlElement memoElment = xmldoucment.CreateElement("memo");
            memoElment.InnerText = "四大名著";
 
            addElement.AppendChild(nameElement);
            addElement.AppendChild(priElement);
            addElement.AppendChild(memoElment);
 
            root.AppendChild(addElement);
 
 
            //modify
 
            XmlNodeList xmlNodeList = root.SelectNodes("/books/book[price>10]");
            foreach (XmlNode node in xmlNodeList)
            {
                Console.WriteLine(node.OuterXml);
            }
 
            //将xmlNode转换为xmlElement以便调用SetAttribute,xmlNode没有这个方法。
            //xmlElement是间接继承的xmlNode的,所以里面的属性和方法肯定要比xmlNode里面的多
            XmlElement selectNode = (XmlElement)(root.SelectSingleNode("/books/book[name='哈里波特']"));
 
           //获取属性值的两种方式
            string s = selectNode.GetAttribute("id");
            var s2 = selectNode.Attributes["id"].Value;
 
            //得到属性
            XmlAttribute attr = selectNode.GetAttributeNode("id");
 
            //修改价格
            selectNode.GetElementsByTagName("price").Item(0).InnerText = "56";
 
 
            //修改属性
            selectNode.SetAttribute("id""B02");//xmlElement才能setAttribute,XmlNode是不可以的
 
            XmlNode xnode = root.SelectSingleNode("/books/book[name='哈里波特']");
 
            Console.WriteLine(xnode.Attributes["id"].Value);//Attributes只有get属性,没有set属性,所以不能赋值给它。如果想要赋值需要用xmlElement
            Console.WriteLine(selectNode.OuterXml);
            //
 
 
            //delete
 
            selectNode.ParentNode.RemoveChild(selectNode);
 
 
            //创建Cdata块
            XmlCDataSection cdata = xmldoucment.CreateCDataSection("<font color=\"red\">这是语文老师的批注</font>");
            XmlElement teacherCommentNode = xmldoucment.CreateElement("Teacher");
            teacherCommentNode.AppendChild(cdata);
            root.AppendChild(teacherCommentNode);
 
            //读取CData节点
            XmlCDataSection cdataSection = (XmlCDataSection)teacherCommentNode.FirstChild;
            Console.WriteLine(cdataSection.InnerText.Trim());
 
            XmlNode nodetemp = root.SelectSingleNode("/books/book/name/text()");//使用text()输出的outxml与不使用的有些不同,
//text(): 新书
//不带text(): <name> 新书<name/>
 //对于”//name“这种写法并不是非常理解,但是可以通过这种写法找出文档内所有的此节点,很强大。
            XmlNodeList nodeList = xmldoucment.SelectNodes("//name");//or root.selectNodes("//name");
 
            Console.WriteLine(nodeList[0].OuterXml);
            Console.WriteLine(nodetemp.OuterXml);
            Console.WriteLine(root.OuterXml);
 
 
            xmldoucment.Save(@"D:\books.xml");
            Console.ReadKey();
        }
    }
}
加载的xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<books>
  <book id="B01">
    <name>哈里波特</name>
    <price>15</price>
    <memo>这是一本很好看的书。</memo>
  </book>
  <book>
    <name>新书</name>
    <price>20</price>
    <memo>新书更好看。</memo>
  </book>
</books>


最终输出的是:

<?xml version="1.0" encoding="UTF-8"?>
<books>
  <book>
    <name>新书</name>
    <price>20</price>
    <memo>新书更好看。</memo>
  </book>
  <book id="B04">
    <name>三国演义</name>
    <price>60</price>
    <memo>四大名著</memo>
  </book>
  <Teacher><![CDATA[<font color="red">这是语文老师的批注</font>]]></Teacher>
</books>


另外,可以为操作xm建立方法:比如

  1.   /// <summary>    
  2.         /// 创建节点    
  3.         /// </summary>    
  4.         /// <param name="xmldoc"></param>  xml文档  
  5.         /// <param name="parentnode"></param>父节点    
  6.         /// <param name="name"></param>  节点名  
  7.         /// <param name="value"></param>  节点值  
  8.         ///   
  9.         public void CreateNode(XmlDocument xmlDoc,XmlNode parentNode,string name,string value)  
  10.         {  
  11.             XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, null);  
  12.             node.InnerText = value;  
  13.             parentNode.AppendChild(node);  
  14.         }  
  15.     }    

Crate xml:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
 
namespace CreateXMLTEST
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument xmldoucument = new XmlDocument();
            XmlNode declaration = xmldoucument.CreateXmlDeclaration("1.0""utf-8""yes");
            xmldoucument.AppendChild(declaration);
 
            XmlElement root = xmldoucument.CreateElement("Books");
 
 
            XmlElement element1 = xmldoucument.CreateElement("Book");
 
            XmlAttribute attibute = xmldoucument.CreateAttribute("Id");
            attibute.Value = "a01";
            element1.Attributes.Append(attibute);
 
            XmlElement elementname = xmldoucument.CreateElement("Name");
            elementname.InnerText = "<<Lucas>>";
            element1.AppendChild(elementname);
 
            root.AppendChild(element1);
            xmldoucument.AppendChild(root);
 
            //XmlNode node = root.SelectSingleNode("/Books/Book[Name='<<Lucas>>']");
            XmlNode node = root.SelectSingleNode("Book");//通过SelectSingleNode方法获得当前节点下的Book子节点
 
            node.InnerText = "hello";
 
            Console.WriteLine(xmldoucument.OuterXml);
            //xmldoucument.Save(@"D:\3\1.xml");
 
 
            Console.ReadKey();
        }
    }
}

参考的范例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
 
namespace TestXml
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlElement theBook = null, theElem = null, root = null;
            XmlDocument xmldoc = new XmlDocument();
            try
            {
                xmldoc.Load(@"C:\Users\v-chazuo\Documents\visual studio 2015\Projects\TestAppConfig\TestXml\bin\Books.xml");
                root = xmldoc.DocumentElement;
 
 
                //---  新建一本书开始 ----
                theBook = xmldoc.CreateElement("book");
                theElem = xmldoc.CreateElement("name");
                theElem.InnerText = "新书";
               
                theBook.AppendChild(theElem);
 
                theElem = xmldoc.CreateElement("price");
                theElem.InnerText = "20";
                theBook.AppendChild(theElem);
 
                theElem = xmldoc.CreateElement("memo");
                theElem.InnerText = "新书更好看。";
                theBook.AppendChild(theElem);
                root.AppendChild(theBook);
                Console.Out.WriteLine("---  新建一本书开始 ----");
                Console.Out.WriteLine(root.OuterXml);
                //---  新建一本书完成 ----
 
                //---  下面对《哈里波特》做一些修改。 ----
                //---  查询找《哈里波特》----
                theBook = (XmlElement)root.SelectSingleNode("/books/book[name='哈里波特']");
                Console.WriteLine("---  查找《哈里波特》 ----");
                Console.WriteLine(theBook.OuterXml);
                //---  此时修改这本书的价格 -----
                theBook.GetElementsByTagName("price").Item(0).InnerText = "15";//getElementsByTagName返回的是NodeList,所以要跟上item(0)。另外,GetElementsByTagName("price")相当于SelectNodes(".//price")。
                Console.Out.WriteLine("---  此时修改这本书的价格 ----");
                Console.Out.WriteLine(theBook.OuterXml);
                //---  另外还想加一个属性id,值为B01 ----
                theBook.SetAttribute("id""B01");
                Console.Out.WriteLine("---  另外还想加一个属性id,值为B01 ----");
                Console.Out.WriteLine(theBook.OuterXml);
                //---  对《哈里波特》修改完成。 ----
                
                //---  再将所有价格低于10的书删除  ----
                theBook = (XmlElement)root.SelectSingleNode("/books/book[@id='B02']");
                Console.Out.WriteLine("---  要用id属性删除《三国演义》这本书 ----");
                Console.Out.WriteLine(theBook.OuterXml);
                theBook.ParentNode.RemoveChild(theBook);
                Console.Out.WriteLine("---  删除后的XML ----");
                Console.Out.WriteLine(xmldoc.OuterXml);
 
                //---  再将所有价格低于10的书删除  ----
                XmlNodeList someBooks = root.SelectNodes("/books/book[price<10]");
                Console.Out.WriteLine("---  再将所有价格低于10的书删除  ---");
                Console.Out.WriteLine("---  符合条件的书有 " + someBooks.Count + "本。  ---");
 
                for (int i = 0; i < someBooks.Count; i++)
                {
                    someBooks.Item(i).ParentNode.RemoveChild(someBooks.Item(i));
                }
                Console.Out.WriteLine("---  删除后的XML ----");
                Console.Out.WriteLine(xmldoc.OuterXml);
 
                xmldoc.Save("books.xml");//保存到books.xml
 
                Console.In.Read();
            }
            catch (Exception e)
            {
                Console.Out.WriteLine(e.Message);
            }
        }
    }
}
 
selectNodes and SelectSingleNode的参数都是xPath,下面说一些常用的xPath

选取节点

XPath 使用路径表达式在 XML 文档中选取节点。节点是通过沿着路径或者 step 来选取的。

下面列出了最有用的路径表达式:

表达式 描述
nodename 选取此节点的所有子节点。
/ 从根节点选取。
// 从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置。
. 选取当前节点。
.. 选取当前节点的父节点。
@

选取属性。

text()                                      当前节点的所有文本节点

实例

在下面的表格中,我们已列出了一些路径表达式以及表达式的结果:

路径表达式 结果
bookstore 选取 bookstore 元素的所有子节点。
/bookstore

选取根元素 bookstore。

注释:假如路径起始于正斜杠( / ),则此路径始终代表到某元素的绝对路径!

bookstore/book 选取属于 bookstore 的子元素的所有 book 元素。
//book 选取所有 book 子元素,而不管它们在文档中的位置。
bookstore//book 选择属于 bookstore 元素的后代的所有 book 元素,而不管它们位于 bookstore 之下的什么位置。
//@lang 选取名为 lang 的所有属性。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值