Thursday, December 24, 2009

How to update an xml file with XmlDocument

Used Classes
XmlDocument
XmlNodeList

Before running the code our xml looks like this:

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

After running the code our xml becomes this:

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

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){
if(!Page.IsPostBack){
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Server.MapPath("categories.xml"));

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
xmlDoc.Save(Server.MapPath("categories.xml"));
Response.Write("XML File updated!");
}
}

</script>