简体   繁体   English

使用LINQ将xml属性更新为XML

[英]Update xml attributes with LINQ to XML

I have an XML file like this: 我有一个像这样的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="" />

After remove an element for ex: id=1;and after that it's like id=2,id=3 id=4. 在删除ex的元素后:id = 1;之后就像id = 2,id = 3 id = 4。 My problem is i want to update XML like id=1 id=2 and id=3. 我的问题是我想更新XML,例如id = 1 id = 2和id = 3。 How can i do that? 我怎样才能做到这一点?

If I understand what you're asking... 如果我明白你的要求...

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

This assumes that you have already removed the first URUN element (with id=1) and you want to update the rest to have sequential IDs starting at 1. 假设您已经删除了第一个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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM