2013-08-21 58 views
0

我有一個XML看起來像這樣Silverlight的XML在特殊位置(LINQ)

<root> 
    <name value="test"> 
     <contact> 
      <id>1</id> 
      <Name>myname mylastname</Name> 
      <phone> 
       <number1_1>123456789</number1_1> 
       <number2_1>987654321</number2_1> 
      </phone> 
     </contact> 
     <contact> 
      <id>2</id> 
      <Name>myname mylastname</Name> 
      <phone> 
       <number1_2>123456789</number1_2> 
       <number2_2>987654321</number2_2> 
      </phone> 
     </contact> 
    </name> 
    <name value="test1"> 
     <contact> 
      <id>1</id> 
      <Name>myname mylastname</Name> 
      <phone> 
       <number1_1>123456789</number1_1> 
       <number2_1>987654321</number2_1> 
      </phone> 
     </contact> 
    </name> 
</root> 

與此代碼,我可以添加一個新的節點添加節點,但它的名字值下始終添加測試。我如何在名稱值test1下添加它?

xmldoc.Element("root").Element("Name").Add( 
    new XElement("contact", 
      new XElement("id", "2"), 
      new XElement("Name", "notset"), 
      new XElement("phone", 
       new XElement("number1_1", "notset"), 
       new XElement("number2_1", "notset") 

      ) 
     ) 
    ); 

有人可以給我提示或一行代碼我怎麼能做到這一點!

問候馬丁

回答

0

Element("name")返回該名稱匹配第一個元素。這就是爲什麼你要查詢你的<name>元素。

.Elements("Name").First(x => (string)x.Attribute("value") == "test1") 

它應該做的伎倆。整個代碼看起來像這樣:

xmldoc.Element("root") 
     .Elements("Name").First(x => (string)x.Attribute("value") == "test1").Add( 
    new XElement("contact", 
      new XElement("id", "2"), 
      new XElement("Name", "notset"), 
      new XElement("phone", 
       new XElement("number1_1", "notset"), 
       new XElement("number2_1", "notset") 

      ) 
     ) 
    ); 
+0

謝謝,它的伎倆 – user2367263