好的,我有一个如下所示的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>现在,首先,我将返回他们的ID号码是什么,所以,我会有"2“。在此基础上,我需要进入并编辑其中的字段,然后重新保存xml。因此,基本上我需要的是打开文件,找到用户ID=" 2“的信息,然后重新保存用户2中具有不同值的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以外的任何内容
~谢谢!
发布于 2009-10-07 16:57:37
有多种方法可以做到这一点--这是使用XmlDocument,它适用于XML1.x及更高版本,只要.NET文档不太长,就可以很好地工作:
// 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");
}如果您使用的是XML3.5或更高版本,那么您还可以使用Linq- to - .NET来使用一种更简单的方法来操作您的XML文档。
Marc
发布于 2009-10-07 17:12:12
看看这个问题,应该可以使用Linq-to-XML得到答案。这涉及到写到控制台窗口,但原理是相同的。
发布于 2009-10-07 17:16:27
您可以使用XmlDocument来执行以下操作:
var doc = new XmlDocument();
doc.Load("1.xml");
var node = doc.SelectSingleNode(@"//User[@ID='2']");
node.SelectSingleNode("password").InnerText="terces";
doc.Save("1.xml");https://stackoverflow.com/questions/1532852
复制相似问题