Thursday 9 June 2011

XML - Amending an Element in a XML Document

Now we can create and write to a XML Document, we can move onto demonstating how to amend an element in a document.

Again, first in c#

string filename = "categories.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Server.MapPath(filename));

XmlNode node = xmlDoc.SelectSingleNode("/CategoryList/Category[@ID='03']/MainCategory");
//node.Attributes[0].Value = "03";

node.Name.ToString();
if (node.Name == "MainCategory")
{
node.InnerXml = "3";
}

xmlDoc.Save(Server.MapPath(filename));

and in vb.net

Dim filename As String = "categories.xml"
Dim xmlDoc As XmlDocument = New XmlDocument()
xmlDoc.Load(Server.MapPath(filename))

Dim node As XmlNode = xmlDoc.SelectSingleNode("/CategoryList/Category[@ID='03']/MainCategory")

node.Name.ToString()
If node.Name = "MainCategory" Then
node.InnerXml = "3"
End If

xmlDoc.Save(Server.MapPath(filename))

No comments:

Post a Comment