C#操作XML文件入门

 

以知已XML文件

<? xml version=”1.0” encoding=”gb2312” ?>

<bookstore>

<book genre=”fantasy” ISBN=”2-3631-4”>

<titel>Oberon’s Legacy</titel>

<author>123456789</author>

<price>12.3</price>

</book>

</bookstore>

 

1.       <bookstroe>节点中插入一个<book>节点

XmlDocument xmlDoc=new XmlDocument();

xmlDoc.Load(“bookstore.xml”);//也可以用@”具体的路径”,@”C:/bookstore.xml”

 

XmlNode root=xmlDoc.SelectSingleNode(“bookstore”);//查找<bookstore>

XmlElement xe1=xmlDoc.CreateElement(“book”);//创建一个<book>节点

Xe1.SetAttribute(“genre”,”wzk”);//设置该节点genre属性

Xe1.SetAttribute(“ISBN”,”2-3631-4”);//设置改节点ISBN属性

 

XmlElement xe2=xmlDoc.CreateElement(“title”);

Xe2.InnerText=”xml文件操作”;

Xe1.AppendChild(xe2);//添加到<book>节点中

 

xmlElement xe3=xmlDoc.CreateElement(“author”);

xe3.InnerText=”houj”;

xe1.AppendChild(xe3);

 

xmlElement xe4=xmlDoc.CreateElement(“price”);

xe4.InnerText=”15.3”;

xe1.AppendChild(ex4);

 

root.AppendChild(xe1);//添加到<bookstore>节点中

xmlDoc.Save(“bookstore.xml”);

 

2.       修改节点:将genre属性值为 houj 的节点的的genre值改为 updatahouj,将该节点的子节点<author>的文件修改为 hjm

xmlNodeList nodeList=xmlDoc.SelectSingleNode(“bookstore”).ChildNodes;//获取bookstore节点下的所有子节点

foreach(XmlNode xn in nodeList)

{

   XmlElement xe=(XmlElement)xn;//将子节点转化为XmlElement;

   If(xe.GetAttribute(“genre”)==”houj”)

   {

      Xe.SetAttribute(“genre”,”updatehouj”);

XmlNodeList nls=xe.ChildNodes;//继续获取xe子节点的所有子节点。

foreach(XmlNode xn1 in nls)

{

   xmlElement xe2=(xmlElement)xn1;

   if(xe2.Name==”author”)

   {

      Xe2.InnerText=”hjm”;

      Break;

}

}

Break;

}

}

xmlDoc.Save(“bookstore.xml”);

 

3.       删除<book genre=”fantasy” ISBN=”2-3631-4”>节点的genre属性,删除<book genre=”updatehouj” ISBN=”2-3631-4” >节点

XmlNodeList xnl=xmlDoc.SelectSingleNode(“bookstore”).ChildNodes;

Foreach(XmlNode xn in xnl)

{

   XmlElement xe=(xmlElement)xn;

   If(xe.GetAttribure(“genre”)==”fantasy”)

   {

      Xe.RemoveAttribure(“genre”);//删除genre属性

}

Else if(xe.GetAttribure(“genre”==”updatehouj”))

{

   Xe.RemoveAll();//删除该节点的全部内容

}

}

XmlDoc.Save(“bookstore.xml”);

 

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);

}

}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值