C#操作XML简明教程

在网上找了一些教程看了看,觉得还是这个最简明了,大家只要把这个代码看完一遍,XML基本操作全明白了,现在我也收藏一下。

 

已知有一个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);
//显示子节点点文本
    }

   }
 

解析XML【C#】

 1.XML元素
XML元素包含一个开标记、元素中的数据、闭标记
例如:<book>book name</book>
其中book是元素名称  book name是元素数据
元素名称区分大小写
每一个XML文档中必须有一个根元素
2.XML属性
属性添加在元素的开标记内
<book titile = "book name"></book>或者<book title = 'book name'></book>
属性的值可以用双引号也可以用单引号
3.元素与属性举例
<book><title>book name</title></book>
<book title = "book name"></book>
上述两种没有本质的区别,但使用时建议使用第一种,因为可以对元素增加属性或子元素,但是不能这样操作属性。
4.XML读取解析
DOM解析XML文档:XML的文档结构是个树状结构
DOM的类在System.Xml中
XmlDocument:用于加载XML文件存放的磁盘位置
XmlNode:这个类表示文档书中的一个节点
XmlNodeList:表示一个节点的集合
XmlElement:表示XML文档中的一个元素
XmlAttribute:表示XML的一个属性
XmlText:表示开标记和闭标记之间的文本
(1)XmlDocument:加载xml文档
例:XmlDocument document = new XmlDocument();
    document.load(@"D:\C#\books.xml");
(2)XmlElement:用于返回一个元素实例
   XmlElement element = document.DocumentElement; //常用来返回一个根节点
   XmlElement类包含许多方法和属性,可以处理树的节点和属性
   1)FirstChild:返回根元素节点后的第一个子节点
   2)LastChild:返回根元素节点后的最后一个子节点
   3)ParentNode:返回当前元素的父节点
   4)NextSibling:返回当前节点的父节点下的下一个节点
   5)HasChildNodes:用来检查当前元素是否有子元素
(3)XmlText:表示开关标记之间的文本,是特殊的节点,属性有:
   1)InnerText:获取当前节点范围内的所有子节点的文本连接起来的字符串
   2)InnerXml:获取当前节点范围内的所有子节点的文本连接起来的字符串,包含标记
5.XML修改解析
 (1)创建节点

   创建节点方法:
   1)CreateElement:用来创建XmlDocument类型的节点
   2)CreateAttribute:用来创建XmlAttribute类型的节点
   3)CreateTextNode:用来创建XmlTextNode类型的节点
   4)CreateNode:用来创建任意类型的节点,包含上述三种以及其他
   创建节点后添加操作:
   1)AppendChild:把创建的节点类型追加到XmlNode类型或其他派生类型的节点后
   2)InsertAfter:将新节点插入到特定的位置
   3)InsertBefore:将新节点插入到特定位置
 (2)删除节点
  1)RemoveChild:删除当前节点范围内的一个指定的子节点
  2)RemoveAll:删除该节点范围内的所有子节点
 (3)修改节点
  1)ReplaceChild:用新子节点替换旧子节点
6.XML查询解析
 (1)使用XmlDocument 方法

   XmlDocument document = new XmlDocument();
   document.Load(filePath);
   XmlNodeList list = document.GetElementsByTagName("book");
   foreach (XmlNode node in list) 
   {
     listBox1.Items.Add(node.Name);//listBox1类型是ListBox
   }
 (2)使用XPath选择特定的节点的方法
  1)SelectSingleNode:用来选择一个节点,如果有多个,则返回第一个节点
  2)SelectNodes:返回一个节点的集合,类型是XmlNodesList
 选择特定的节点的方法参数XPath
  XPath是XML文档的查询语言

7.XML解析代码

[csharp]  view plain copy
  1. using System;  
  2. using System.Data;  
  3. using System.Drawing;  
  4. using System.Text;  
  5. using System.Windows.Forms;  
  6. using System.IO;  
  7. using System.Xml;  
  8.   
  9. namespace Update  
  10. {  
  11.     public partial class Form1 : Form  
  12.     {  
  13.   
  14.         string filePath = Directory.GetCurrentDirectory() + @"\uploadXML.xml";  
  15.         public Form1()  
  16.         {  
  17.             InitializeComponent();  
  18.         }  
  19.   
  20.         //读取xml  
  21.         private void button1_Click(object sender, EventArgs e)  
  22.         {  
  23.   
  24.             if (File.Exists(filePath))  
  25.             {  
  26.   
  27.                 XmlDocument document = new XmlDocument();  
  28.                 document.Load(filePath);  
  29.                 XmlNode root = (XmlNode)document.DocumentElement;  
  30.                 //循环展示成树状  
  31.                 xmlProcess(root,0);  
  32.   
  33.             }  
  34.             
  35.         }  
  36.           
  37.   
  38.         /* 
  39.          * 循环展示成树状 
  40.          */  
  41.         private void xmlProcess(XmlNode root,int i)   
  42.         {  
  43.   
  44.             if (root == null)   
  45.             {  
  46.                 return;  
  47.             }  
  48.             if (root is XmlElement)   
  49.             {  
  50.                 listBox1.Items.Add(root.Name.PadLeft(root.Name.Length + i));  
  51.                 if (root.HasChildNodes)   
  52.                 {  
  53.                     xmlProcess(root.FirstChild,i+2);  
  54.                 }  
  55.                 if (root.NextSibling != null)   
  56.                 {  
  57.                     xmlProcess(root.NextSibling, i);  
  58.                 }  
  59.   
  60.             }  
  61.             else if (root is XmlText)   
  62.             {  
  63.                 string text = ((XmlText)root).Value;  
  64.                 listBox1.Items.Add(text.PadLeft(text.Length+i));  
  65.             }  
  66.         }  
  67.   
  68.         //读取文本节点  
  69.         private void button2_Click(object sender, EventArgs e)  
  70.         {  
  71.             XmlDocument document = new XmlDocument();  
  72.             document.Load(filePath);  
  73.             XmlNode root = (XmlNode)document.DocumentElement;  
  74.             string values = root.InnerText;  
  75.             string values2 = root.InnerXml;  
  76.             string values3 = root.Value;  
  77.             MessageBox.Show(values);  
  78.             MessageBox.Show(values2);  
  79.             MessageBox.Show(values3);  
  80.         }  
  81.         //添加节点  
  82.         private void button3_Click(object sender, EventArgs e)  
  83.         {  
  84.             XmlDocument document = new XmlDocument();  
  85.             document.Load(filePath);  
  86.             XmlElement root = document.DocumentElement;  
  87.   
  88.             //create node  
  89.             XmlElement newBook = document.CreateElement("book");  
  90.             XmlElement newTitle = document.CreateElement("title");  
  91.             XmlElement newAuthor = document.CreateElement("author");  
  92.               
  93.             //create text  
  94.             XmlText titleText = document.CreateTextNode("new title");  
  95.             XmlText authorText = document.CreateTextNode("new author");  
  96.   
  97.             //insert  
  98.             newTitle.AppendChild(titleText);  
  99.             newAuthor.AppendChild(authorText);  
  100.   
  101.             newBook.AppendChild(newTitle);  
  102.             newBook.AppendChild(newAuthor);  
  103.   
  104.             root.AppendChild(newBook);  
  105.   
  106.             //save  
  107.             document.Save(filePath);  
  108.   
  109.   
  110.   
  111.   
  112.         }  
  113.         //删除节点  
  114.         private void button4_Click(object sender, EventArgs e)  
  115.         {  
  116.             XmlDocument document = new XmlDocument();  
  117.             document.Load(filePath);  
  118.             XmlElement root = document.DocumentElement;  
  119.             if (root.HasChildNodes)   
  120.             {  
  121.                 XmlNode old = root.LastChild;  
  122.                 root.RemoveChild(old);  
  123.             }  
  124.   
  125.             document.Save(filePath);  
  126.   
  127.         }  
  128.         //修改节点  
  129.         private void button5_Click(object sender, EventArgs e)  
  130.         {  
  131.             XmlDocument document = new XmlDocument();  
  132.             document.Load(filePath);  
  133.             XmlElement root = document.DocumentElement;  
  134.             if (root.HasChildNodes)  
  135.             {  
  136.                 XmlNode oldNode = root.LastChild;  
  137.                 XmlNode newNode = document.CreateElement("Book");  
  138.                 root.ReplaceChild(newNode, oldNode);  
  139.             }  
  140.   
  141.             document.Save(filePath);  
  142.   
  143.         }  
  144.         //查询节点  
  145.         private void button6_Click(object sender, EventArgs e)  
  146.         {  
  147.             listBox1.Items.Clear();  
  148.   
  149.             XmlDocument document = new XmlDocument();  
  150.             document.Load(filePath);  
  151.             XmlNodeList list = document.GetElementsByTagName("book");//要查询的的节点名  
  152.             foreach (XmlNode node in list)   
  153.             {  
  154.                 listBox1.Items.Add(node.Name);  
  155.             }  
  156.         }  
  157.   
  158.     }  
  159. }  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值