How to update an xml file with XmlDocument?

Used Classes


Before running the code our xml looks like this:

<?xml version="1.0" encoding="utf-8"?>
  <Category ID="01">
    <Description>This is a list my XML articles.</Description>

After running the code our xml becomes this:

<?xml version="1.0" encoding="utf-8"?>
  <Category ID="01">
    <Description>This is now my ASP.NET list.</Description>

The code which does that looks like this:

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Xml" %>
<%@ Page Language="C#" Debug="true" %>

<script  runat="server">
void Page_Load(object sender, System.EventArgs e){
        XmlDocument xmlDoc = new XmlDocument();

        XmlNodeList nodeList = xmlDoc.SelectNodes("/CategoryList/Category[@ID='01']");

        // update MainCategory 
        nodeList[0].ChildNodes[0].InnerText = "ASP.NET";
        // update Description 
        nodeList[0].ChildNodes[1].InnerText = "This is now my ASP.NET list.";
        // update Active 
        nodeList[0].ChildNodes[2].InnerText = "false";

        // Don't forget to save the file
        Response.Write("XML File updated!");

Filed under:


# Jerry Pisk said:

So much for using XML. Why exactly do you hardcode node positions? XML is meant to be extensible (that's what the X stands for) and by hardcoding node positions you're assuring your code is going to break.

Wednesday, May 19, 2004 5:44 PM
# Sonu Kapoor said:

Maybe you can show me how to correct the code ?


Wednesday, May 19, 2004 5:47 PM
# Jerry Pisk said:

// update MainCategory
nodeList[0].SelectSingleNode("MainCategory ").InnerText = "ASP.NET";

Add error checking...

Thursday, May 20, 2004 4:01 PM
# Sonu Kapoor said:

Jerry you mean something like ?

if(nodeList.Count > 0)
// update Main Category
nodeList[0].SelectSingleNode("MainCategory ").InnerText = "ASP.NET";


Thursday, May 20, 2004 7:28 PM
# Jerry Pisk said:

How can one post <pre> comments in .Text?

Thursday, May 20, 2004 7:38 PM
# Sonu Kapoor said:

Ah....I know now what you mean Jerry, many thanks for the information. I will update the entry with your reference in it. I am glad that somebody is here to help me with the "XML How to's".

I have no clue how the <pre> can be used in the comment section. I guess its not possible.


Thursday, May 20, 2004 7:42 PM
# cpms said:


How can add new node?

Wednesday, June 24, 2009 4:25 AM
# srinivasaprabhu said:

Nice code.Thnks for doing so.. mr.Sonukapoor.Abut adding new child & parent node??

Thursday, August 26, 2010 6:32 AM
# rajendar.paisa said:

good article

for more info

Thursday, August 18, 2011 3:17 PM