Question

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.

Was it helpful?

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"

OTHER TIPS

Check these links which can help a lot (using linq is one of the best ways):

  1. add data to existing xml file using linq
  2. Adding element to XML using linq to XML
  3. Insert new XML node using LINQ

As an example I just did:

    string customers = "<Customers><Customer Id=\"1\" Name=\"abc\"/><Customer Id=\"2\" Name=\"efg\"/></Customers>";
    XDocument doc = XDocument.Parse(customers);
    XElement element = new XElement("Customer", new XAttribute("Id", "3"), new XAttribute("Name", "test"));
    doc.Element("Customers").Add(element);
    doc.Save(xmlfilepath);

To Modify:

    var myElement = doc.Elements("Customers").Elements("Customer").Where(el => el.Attribute("Id").Value == "2").SingleOrDefault();
    if (myElement != null)
        myElement.SetAttributeValue("Name", "aaabbbccc");

You are using LINQ to XML which is perhaps the easiest of the .NET XML APIs to use:

For the first part: updating the value of an attribute, you need to get the XAttribute instance for the Name attribute and change its value:

custElement.Attribute("Name").Value = "aaabbbccc";

assuming CustElement is the right <Customer> element.

For the second part: append another element, to insert an element after another use the AddAfterSelf method of XNode (parent of XElement), so given rootElement being an XElement for the <Customers> element:

rootElement.LastNode.AddAfterSelf(new XElement("Customer",
                                               new XAttribute("Id", 3),
                                               new XAttribute("Name", "test")));

(The first parameter of XElement's constructor is its name, subsequent ones are content—either attributes (as in this case) or child nodes. There are multiple other ways to do this: eg. Add(object) to append to an XElement wrapping the <Customers> element, but in practice one tends to have ones own preference and stick to it (a small consistency making code a little simpler).

For the third part: get customer by id we can just use a LINQ comprehension expression:

var matches = (from cust in customersElement.Elements("Customer")
              where (int)cust.Attribute("Id") == theTargetId
              select cust)
              .Single();

(This will throw if anything other than exactly one match is found, use SingleOrDefault to return null on not found.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top