+-

好的,所以,我有一个看起来像这样的xml文件:
<?xml version="1.0"?>
<Users>
<User ID="1">
<nickname>Tom</nickname>
<password>a password</password>
<host>[email protected]</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字段替换 - 乐贴网