如何使用C#从xml文件读取,更新,删除数据 [英] how to read, update, delete data from and to xml file with C#

查看:69
本文介绍了如何使用C#从xml文件读取,更新,删除数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用C#从xml文件中插入,读取,更新和删除数据?

how could i insert, read, update and delete data from xml file with using C#?

推荐答案

有多种方法可以实现相同的目的. >
如果要继续按顺序阅读,可以使用XmlReader.

如果要在特定位置读取/更新/删除/插入,可以使用两种方法
1. XmlDocument和XPath.
2. LinQ转XML

对于XmlDocument方法,首先声明变量并加载xml.

There are various ways to achieve the same.

If you want to keep reading sequentially, you can use XmlReader.

If you want to read/update/delete/insert at particular location, you can use two approaches
1. XmlDocument and XPath.
2. LinQ to XML

For XmlDocument approach, First you declare variable and load xml.

XmlDocument xDoc = new XmlDocument();
xDoc.Load("YourFile.Xml");


然后,你读起来就像


Then, you read like

string nodeValue = xDoc .DocumentElement.SelectSingleNode("NodeName").InnerText;



您可以更新值,例如



You can update value like

xDoc.DocumentElement.SelectSingleNode("NodeName").InnerText = newValue;


请注意,在上面的代码中,"NodeName实际上是Xpath.您可以像Node/ChildNode/GrandChildNode这样给它命名,等等.您可以在 ^ ]

希望能有所帮助.如果确实将其标记为答案/赞扬.

谢谢
Milind


Note, that in above code, "NodeName is actually Xpath. You can give it like Node/ChildNode/GrandChildNode and so on. You can find more details about xPath at http://www.w3schools.com/xpath/default.asp[^]

Hope that helps. If it does mark it as answer/upvote.

Thanks
Milind


更好,更简单的方法是利用LINQ TO XML进行插入,更新和删除

检查此处是否给出了LINQ TO XML的所有示例- http://msdn.microsoft.com/en-us /vstudio/bb688087.aspx [ ^ ]
Better and easy way to do is make use of LINQ TO XML to insert,update and delete

Check here all examples are given for LINQ TO XML - http://msdn.microsoft.com/en-us/vstudio/bb688087.aspx[^]


这篇关于如何使用C#从xml文件读取,更新,删除数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆