Reputation: 95
I have an XML file like this:
<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. My problem is i want to update XML like id=1 id=2 and id=3. How can i do that?
Upvotes: 0
Views: 607
Reputation: 140
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);
}
Upvotes: 0
Reputation: 32447
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.
Upvotes: 1