2013-07-08 24 views
1

我有以下結構的XML文檔:如何添加子女,父元素的屬性= X

<position index="x"> 
    <character>y</character> 
</position> 

我需要能夠以一個新的角色加入到基於其索引的位置。例如,其中index =「3」,添加字符「g」。

我知道我可以找到與元素如下:

var query = from positions in myDoc.Descendants("position") 
    where (string)positions.Attribute("index").Value == n 
    select positions; 

,但我有麻煩搞清楚,如果我需要一個類似的一種查詢或建設的識別與屬性值x的元素,然後添加子節點。

回答

1

您的查詢已經返回了要添加到元素,所以它歸結爲:

var query = from positions in myDoc.Descendants("position") 
      where (string)positions.Attribute("index").Value == n 
      select positions; 
foreach (var position in query) 
{ 
    position.Add(new XElement("character", "g")); 
} 
+0

謝謝,@jimmy_keen。我收到以下錯誤:\t'System.Collections.Generic.IEnumerable '不包含'添加'的定義,也沒有擴展方法'添加'接受類型' System.Collections.Generic.IEnumerable '可以找到(你是否缺少使用指令或程序集引用?) – tmoore82

+0

@ tmoore82:你是否加入了'foreach'?我編輯了我的答案,你的代碼應該看起來像這樣才能工作。 –

+0

沒關係。知道查詢只返回了一個值,我試圖在沒有'foreach'的情況下執行。這是錯誤的根源。 – tmoore82

相關問題