Add/Remove nodes or elements to an XML Document

Posted by Techie Cocktail | 11:12 PM | , | 4 comments »

In the article, Update nodes and attributes in Xml document, we saw how to update an element or an attribute value in an Xml Document. It requires you to have a pointer to the node or attribute to update before you can update its value.

Lets say you want to add a new node section to an existing Xml document. For example lets take the same Xml file as used in the earlier article. It contains list of books, each having its name, author and price values. Say you want to add a new book & its details to the existing list of books.

Xml File: books.xml
<?xml version="1.0"?>
<books>
<book name="asp.net">
<author>John</author>
<price>35</price>
</book>
</books>

To add a new node, you don't require to have any pointer using XPath. XMLDocument, XMLElement and its properties and method does it all. We will first see how to add a new book section. After that we will remove the first one using C#.

Add a new node


static void Main(string[] args)
{
string fileName = @"d:\books.xml";

XmlTextReader _xmlTextReader = new XmlTextReader(fileName);
XmlDocument _xmlDocument = new XmlDocument();
_xmlDocument.Load(_xmlTextReader);

//Note: Close the reader object to release the xml file. Else while saving you will get an error that it is
//being used by another process.
_xmlTextReader.Close();

addNode(fileName, _xmlDocument);
}

static void addNode(string fileName, XmlDocument xmlDoc)
{
XmlElement bookElement = xmlDoc.CreateElement("book");
bookElement.SetAttribute("name", "DotNet Made Easy");

XmlElement authorElement = xmlDoc.CreateElement("author");
authorElement.InnerText = "microsoft";
bookElement.AppendChild(authorElement);

XmlElement priceElement = xmlDoc.CreateElement("price");
priceElement.InnerText = "50";
bookElement.AppendChild(priceElement);

xmlDoc.DocumentElement.AppendChild(bookElement);
xmlDoc.Save(fileName);
}

Your Xml file should have new book added and should look like below.

Xml File: books.xml
<?xml version="1.0"?>
<books>
<book name="asp.net">
<author>John</author>
<price>35</price>
</book>
<book name="DotNet Made Easy">
<author>microsoft</author>
<price>50</price>
</book>
</books>

Remove a node
Now lets remove the book - 'asp.net' from the list. The deleteNode() method below will remove the book node whose name="asp.net". Using XPath query we create a pointer to the node that needs to be removed. As book is the child node of the books (root element), RemoveChild() helps to remove the book (child node) from the books (root element).

static void deleteNode(string fileName, XmlDocument xmlDoc)
{
XmlElement _xmlElement = xmlDoc.DocumentElement;

XmlNode _xmlNode = _xmlElement.SelectSingleNode("book[@name='asp']");
_xmlElement.RemoveChild(_xmlNode);
xmlDoc.Save(fileName);
}


As seen from these examples it has become easy to perform almost every Xml task with the use of XML classes in .Net. Happy Coding!

4 comments

  1. lingmaaki // January 14, 2014 at 10:10 PM  

    C# XML operations

    http://csharp.net-informations.com/xml/csharp-xmltutorial.htm

    c# xml tutorial

    ling

  2. Anonymous // April 7, 2015 at 10:10 AM  

    thanks :)

  3. Unknown // November 21, 2017 at 12:41 AM  

    Yes, this article is true. I did all this steps last week. Something goes wrong every hour, ohm I spent much time on this. But it's turned out an easy way. On that time I found the article about how to open .xml file https://wikiext.com/xml. This page is very usefull, for that case if you will a bit confused, or miss some file.

  4. Anonymous // January 28, 2022 at 3:26 PM  

    1xbet korean - Legit Betting | LegitBets.com
    The best febcasino betting site with a great selection of promotions! Get exclusive free spins to 1xbet play games and win big worrione money with our new betting site!