[英]Update xml attributes with LINQ to XML
我有一個像這樣的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="" />
在刪除ex的元素后:id = 1;之后就像id = 2,id = 3 id = 4。 我的問題是我想更新XML,例如id = 1 id = 2和id = 3。 我怎樣才能做到這一點?
如果我明白你的要求...
int i = 1;
foreach (var e in elem.Elements("URUN")) {
e.SetAttributeValue("id", i);
i++;
}
假設您已經刪除了第一個URUN元素(id = 1),並且想要更新其余的元素以具有從1開始的順序ID。
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.