首页 / XML / C#中的XML字段替换
C#中的XML字段替换
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C#中的XML字段替换,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2237字,纯文字阅读大概需要4分钟。
内容图文
![C#中的XML字段替换](/upload/InfoBanner/zyjiaocheng/671/2cec1232122c4a89826f4c0a09c50008.jpg)
好的,所以,我有一个看起来像这样的xml文件:
<?xml version="1.0"?>
<Users>
<User ID="1">
<nickname>Tom</nickname>
<password>a password</password>
<host>anemail@hello.com</host>
<email>anemail</email>
<isloggedin>false</isloggedin>
<permission>10</permission>
</User>
<User ID="2">
<nickname>ohai</nickname>
<password>sercret</password>
<host>my@host</host>
<email>my@email</email>
<isloggedin>false</isloggedin>
<permission>1</permission>
</User>
<Users>
现在,首先,我将返回他们的身份证号码,因此,请病假为“ 2”.
从那开始,我将需要进入并编辑其中的字段,并重新保存xml.
所以基本上我需要的是打开文件,找到用户ID =“ 2”的信息,然后使用用户2内的DIFFERENT值重新保存xml,而不会影响文档的其余部分.
范例:
<User ID="2">
<nickname>ohai</nickname>
<password>sercret</password>
<host>my@host</host>
<email>my@email</email>
<isloggedin>false</isloggedin>
<permission>1</permission>
</User>
//在这里进行更改,最后得到
<User ID="2">
<nickname>ohai</nickname>
<password>somthing that is different than before</password>
<host>the most current host that they were seen as</host>
<email>my@email</email>
<isloggedin>false</isloggedin>
<permission>1</permission>
</User>
等等
摘要:
我需要打开一个文本文件,通过ID号返回信息,编辑信息,重新保存文件.不影响用户2以外的任何其他用户
?谢谢!
解决方法:
您可以通过多种方式执行此操作-这是XmlDocument的一种,它可以在.NET 1.x及更高版本中使用,并且只要XML文档不太长就可以正常工作:
// create new XmlDocument and load file
XmlDocument xdoc = new XmlDocument();
xdoc.Load("YourFileName.xml");
// find a <User> node with attribute ID=2
XmlNode userNo2 = xdoc.SelectSingleNode("//User[@ID='2']");
// if found, begin manipulation
if(userNo2 != null)
{
// find the <password> node for the user
XmlNode password = userNo2.SelectSingleNode("password");
if(password != null)
{
// change contents for <password> node
password.InnerText = "somthing that is different than before";
}
// find the <host> node for the user
XmlNode hostNode = userNo2.SelectSingleNode("host");
if(hostNode != null)
{
// change contents for <host> node
hostNode.InnerText = "the most current host that they were seen as";
}
// save changes to a new file (or the old one - up to you)
xdoc.Save("YourFileNameNew.xml");
}
如果您使用的是.NET 3.5及更高版本,则还可以检查Linq-to-XML,这可能是一种甚至更简单的操作XML文档的方法.
渣
内容总结
以上是互联网集市为您收集整理的C#中的XML字段替换全部内容,希望文章能够帮你解决C#中的XML字段替换所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。