0

linq to xml を使用して 2 番目の要素の属性を更新する方法を教えてください。私はいくつかのコードを書いていますが、機能しません。ユーザー属性を更新するだけです....この種の簡単な質問をして申し訳ありません。

私のXML:

<Settings>
<Settig>
<User id="1" username="Aplha"/>
<Location Nation="USA" State="Miami" />
<Email>user1@hotmail.com</Email>
</Setting>
</Settings>

私のC:

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");
    }
4

1 に答える 1

2

Setting要素を選択します。id=1次のように、引き続き on を選択できます。

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");           
}    
于 2012-11-06T07:38:51.920 に答える