2016-11-13 90 views
0

我想在c#中更新文件中的xml值。更新Xml和C#

下面是XML文件:

<user_Name> 
Florian 
<account> 
<account_Name/> 
<number_lines/> 
<line> 
<line_Id/> 
<line_Date/> 
<line_Desc/> 
<line_Value/> 
</line> 
</account> 
</user_Name> 

我与LINQ试过,我在该行有一个NullReferenceException我试图改变价值

代码:

public void Create_New_Account(string _path_File) 
     { 
      Console.WriteLine(_path_File); 
      string account_Name = "test"; 

      XDocument xmlFile = XDocument.Load(_path_File); 

      var query = from c in xmlFile.Elements("user_Name").Elements("account") 
         select c; 
      Console.WriteLine(query); 

      foreach (XElement account in query) 
      { 
       account.Attribute("account_Name").Value = account_Name; 
      } 
     } 

我也试用XmlDocument:

XmlDocument xmlDoc = new XmlDocument(); 

xmlDoc.Load(xmlFile); 

XmlNode node = xmlDoc.SelectSingleNode("user_Name/account/account_Name"); 
node.Attributes[0].Value = "test"; 

xmlDoc.Save(xmlFile); 

此处同样的错误。 我首先想到我没有通过正确的道路,但它是正确的。 我试图使用文件中的其他元素,仍然无法正常工作。

有人可以给我一个小费,我做错了什么吗?

+0

使用调试器来检查什么是空的。 – SLaks

+0

从c中选择c'没有意义。 – SLaks

+0

我从那里拿过它:http://stackoverflow.com/questions/367730/how-to-change-xml-attribute 使用调试器时,错误发生时,一切都有一个值。但var账户具有所有xml文件作为值 – Andromelus

回答

0

你可以做这样的:

foreach (XElement account in query) 
    account.Element("account_Name").Add(new XAttribute("account_Name", account_Name)); 

更加小心,你可以写一些代码,所以如果属性帐户名不存在,创建它,否则,你将它添加到节点:

var accountNameAttribute = "account_Name"; 
foreach (XElement account in query) 
{ 
    var accountName = account.Element(accountNameAttribute); 
    if (accountName.Attribute(accountNameAttribute) == null) 
     accountName.Add(new XAttribute(accountNameAttribute, account_Name)); 
    else 
     accountName.Attribute(accountNameAttribute).Value = account_Name; 
} 

希望这会有所帮助!

+0

正如Cramiriel所说,我其实不是在寻找属性,而是为了元素。但是我会保留它在任何地方,可能是有用的;) – Andromelus