2012-11-06 4 views
0

linq to xml을 사용하여 두 번째 요소의 속성을 업데이트하는 방법을 알고 있을까요? 나는 약간의 코드를 작성하지만 작동하지 않는다. 단지 사용자 속성 만 업데이트한다 .... 이런 종류의 간단한 질문을하는 것은 유감 스럽다.XML에서 두 번째 요소의 속성을 업데이트하는 방법은 무엇입니까?

내 XML :

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

내 고사 : 당신은 Setting 요소를 선택합니다

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

; 당신은 여전히 ​​다음과 같이 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

관련 문제