2009-10-07 66 views
3

行,所以,我有一个XML文件,它看起来像这样:XML现场更换在C#

<?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>[email protected]</host> 
    <email>[email protected]</email> 
    <isloggedin>false</isloggedin> 
    <permission>1</permission> 
    </User> 
<Users> 

现在,首先,我将有自己的身份证号码是多少回报,所以,生病了“ 2" 。 从那里,我将需要进入,并编辑其中的字段,并重新保存XML。 所以基本上我需要的是打开文件,找到用户ID =“2”的信息,并重新保存用户2内的不同值的xml,而不影响文档的其余部分。

examlpe:

<User ID="2"> 
    <nickname>ohai</nickname> 
    <password>sercret</password> 
    <host>[email protected]</host> 
    <email>[email protected]</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>[email protected]</email> 
    <isloggedin>false</isloggedin> 
    <permission>1</permission> 
    </User> 

总结结束: 我需要打开一个文本文件,返回通过ID号码信息,编辑信息,重新保存文件。不影响用户2以外的任何其他内容

〜谢谢!

回答

4

有多种方法可以做到这一点 - 这是一个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文档的更简单的方法。

Marc

0

您可以使用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"); 
+0

'node.SelectSingleNode( “密码”)InnerText'这是危险的,如果没有 “密码” 节点可以发现 - 你会。猛击到NullReferenceException – 2009-10-07 18:06:19

+0

是的,你是对的。为了简洁,我在这个示例中省略了它,但是如果我编写了更容易出错的示例,会更好。 – 2009-10-08 03:55:11