Search code examples
c#xelement

Update and Add new Tag inside XML


Below is example of my XML:

<Customers>
  <Customer Id="1" Name="abc"/>
  <Customer Id="2" Name="efg"/>
</Customers>

How to update inside this XML using XElement?

<Customer Id="1" Name="aaabbbccc"/>

And How to add new row inside this xml??

<Customers>
  <Customer Id="1" Name="abc"/>
  <Customer Id="2" Name="efg"/>
  <Customer Id="3" Name="test"/>
</Customers>

And, how to get specfied name? For e.g, if 1 then abc, if 2 then efg

Sorry but I have no idea, new to XML and XElement.


Solution

  • I would recommend using LINQ to XML (in namespaces System.Linq and System.Xml.Linq);

    // Load Xml
    string xml = "";
    XDocument doc = XDocument.Parse(xml);
    
    // Get and modify element
    if (doc.Root != null)
    {
        var elementToModify = doc.Root.Elements("Customer").SingleOrDefault(x => x.Attribute("Id").Value == "2");
        if (elementToModify != null) elementToModify.SetAttributeValue("Name", "aaabbbccc");
    }
    
    // Add new Element
    XElement customer = doc.Descendants("Customers").FirstOrDefault();
    if (customer != null) customer.Add(new XElement("Customer", new XAttribute("Id", 3), new XAttribute("Name", "test")));
    
    // OR (maddy's answer)
    doc.Element("Customers").Add(new XElement("Customer", new XAttribute("Id", 3), new XAttribute("Name", "test")));
    
    // OR (Richard's answer)
    doc.Root.LastNode.AddAfterSelf(new XElement("Customer", new XAttribute("Id", 3), new XAttribute("Name", "test")));
    

    EDIT:

    // Get the Name attribute for a specified Id.
    XElement element = doc.Root.Elements("Customer").Single(x => x.Attribute("Id").Value == "1");
    string name = element.Attribute("Name").Value; // will be "abc"