2012-11-06 43 views
0

我可以知道如何使用linq更新第二个元素的属性到xml吗?我写了一些代码,但它不起作用,它只更新用户属性....我很抱歉问这种简单的问题。如何更新XML上的第二个元素的属性?

我的XML:

<Settings> 
<Settig> 
<User id="1" username="Aplha"/> 
<Location Nation="USA" State="Miami" /> 
<Email>[email protected]</Email> 
</Setting> 
</Settings> 

我的CS:

public static void saveSetting(MainWindow main) 
    { 
     XDocument document = XDocument.Load("Setting.xml"); 
     IEnumerable<XElement> query = from p in document.Descendants("User") 
             where p.Attribute("id").Value == "1" 
             select p; 


     foreach (XElement element in query) 
     {    
      string i = "New York"; 
      element.SetAttributeValue("State", i); 
     } 

     document.Save("Setting.xml"); 
    } 

回答

2

您要选择的Setting元素;您仍然可以选择在id=1,像这样:

IEnumerable<XElement> query = from p in document.Descendants("Setting") 
            where p.Element("User").Attribute("id").Value == "1" 
            select p; 

然后更新前选择Location元素:

foreach (XElement element in query) 
{  
    element.Element("Location").SetAttributeValue("State", "New York");   
}  
+0

@ 0070是的,我是这么认为的 - 你需要首先选择'Location'元素,然后设置属性。 – McGarnagle

+0

好的!谢谢 – 0070

相关问题