更新XML与LINQ属性XML

问题描述:

我有一个这样的XML文件:更新XML与LINQ属性XML

<URUN id="1" uName="KT-08" thumb="images_/berjer_/small_/17.jpg" image="images_/berjer_/17.jpg" desc="" />  
<URUN id="2" uName="KT-08" thumb="images_/berjer_/small_/18.jpg" image="images_/berjer_/18.jpg" desc="" />  
<URUN id="3" uName="KT-08" thumb="images_/berjer_/small_/19.jpg" image="images_/berjer_/19.jpg" desc="" /> 
<URUN id="4" uName="KT-08" thumb="images_/berjer_/small_/20.jpg" image="images_/berjer_/20.jpg" desc="" /> 

删除元素后为前:ID = 1;之后,它就像ID = 2,ID = 3 ID = 4。我的问题是我想更新XML像id = 1 id = 2和id = 3。我怎样才能做到这一点?

+0

我想你错过了一些你的示例XML ... – 2011-03-10 23:03:30

如果我理解你的要求......

int i = 1; 
foreach (var e in elem.Elements("URUN")) { 
    e.SetAttributeValue("id", i); 
    i++; 
} 

这假定您已经删除了第一URUN元素(ID = 1),要更新其余的有顺序ID从1开始。

XElement urunlur = XDocument.Load("filepath.xml").Root; 
var uruns = urunlur.Elements("URUN"); 

//the next line will throw an exception if 
// (a) a URUN element exists without an id attribute 
// (b) there is no URUN element with an id = 1 
// (c) a URUN element exists with a non-integer id 

uruns.Single(x => int.Parse(x.Attribute("id").Value) == 1).Remove(); 

var count = uruns.Count(); 
var sorted = uruns.OrderBy(x => x.Attribute("id").Value); 
for(int i = 0; i<count;i++) 
{ 
    sorted.ElementAt(i).SetAttributeValue("id",i+1); 
} 
+0

只要使用'foreach' – abatishchev 2011-03-11 08:36:37