2011-03-10 64 views
0

我有一個這樣的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

回答

1

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

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

這假定您已經刪除了第一URUN元素(ID = 1),要更新其餘的有順序ID從1開始。

0
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