Search code examples
c#xmllinq-to-xmlappendxelement

How to update XML file content with XDocument


I have a XML file that contains this:

<?xml version="1.0" encoding="utf-8" ?> 
<TokenToCardMapping>
  <pair key ="2313123124122512" value="3412412512512512"/>
  <pair key ="3414125121259723" value="3749327923749723"/>
</TokenToCardMapping>

I am looking for way to add a new pair element to the TokenToCardMapping descendants with XDocument or XElement.

I have the key and value as strings and I just want to add a new pair.

if my new key and value are: 111111111111 , 222222222222 I want to update the xml to look like this:

<?xml version="1.0" encoding="utf-8" ?> 
<TokenToCardMapping>
  <pair key ="2313123124122512" value="3412412512512512"/>
  <pair key ="3414125121259723" value="3749327923749723"/>
  <pair key ="111111111111" value="222222222222"/>
</TokenToCardMapping>

Solution

  • It is easy with LINQ to XML

    // create new element
    var newElement = new XElement("pair",
                     new XAttribute("key","111111111111"
                     new XAttribute("value","222222222222"));
    
    // load the XML Document
    var xDoc = XDocument.Load("path");
    
    // Add new element to the root element
    xDoc.Root.Add(newElement);
    
    //And save the XML file
    xDoc.Save("path")
    

    Note: You need to add a reference to System.Xml.Linq.dll from your project

    And I would recommend you read the LINQ to XML tutorial for more details.