Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I update a specific XElement?

Tags:

c#

xml

What is the best way to update an XElement (update the value of itemNumber of element Pen) in this XML?

<?xml version="1.0" encoding="utf-8"?>
<MyStore>
  <Category>
    <itemName>Pen</itemName>
    <itemNumber>12</itemNumber>
  </Category>
  <Category>
    <itemName>Paper</itemName>
    <itemNumber>23</itemNumber>
  </Category>
</MyStore>
like image 866
paradisonoir Avatar asked Jul 23 '09 22:07

paradisonoir


2 Answers

XDocument doc;
...
XElement penItemValue = doc
     .Elements("MyStore")
     .Elements("Category")
     .Elements("itemName")
     .Single(itemName => itemName.Value == "Pen")
     .Parent
     .Element("itemValue");
penItemValue.Value = "123";
like image 102
Pavel Minaev Avatar answered Sep 19 '22 15:09

Pavel Minaev


You could find it and update it using LinqToXml:

XElement root = XElement.Load("myXml.xml");

var penCategory = from category in root.Descendants("Category")
                  where category.Element("itemName") != null 
                     && category.Element("itemName").Value == "Pen"
                  select category;

penCategory.Element("itemName").Value = updatedValue;
like image 33
womp Avatar answered Sep 19 '22 15:09

womp