使用LINQ to XML更新xml属性

时间:2011-03-10 23:00:51

标签: .net xml linq 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。我的问题是我想更新像id = 1 id = 2和id = 3的XML。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

如果我明白你在问什么......

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

这假设您已经删除了第一个URUN元素(id = 1),并且您希望更新其余元素以使序列ID从1开始。

答案 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);
}