Thursday 9 June 2011

XML - Write to an XML Documnent

Next up is a quick bit of coding to show how to dynamically insert a new element to a XML Document.

In c# use:

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

XmlNode root = xmlDoc.DocumentElement;
XmlElement ListNode = xmlDoc.CreateElement("CategoryList");

XmlElement childNode = xmlDoc.CreateElement("MainCategory");

XmlElement parentNode = xmlDoc.CreateElement("Category");
parentNode.SetAttribute("ID", "04");
xmlDoc.DocumentElement.PrependChild(parentNode);
// Set attribute name and value!

XmlElement mainNode = xmlDoc.CreateElement("MainCategory");
XmlElement descNode = xmlDoc.CreateElement("Description");
XmlElement activeNode = xmlDoc.CreateElement("Active");

// retrieve the text
XmlText categoryText = xmlDoc.CreateTextNode(txt_maincategory.Text);
XmlText descText = xmlDoc.CreateTextNode(txt_description.Text);
XmlText activeText = xmlDoc.CreateTextNode(txt_active.Text);

// append the nodes to the parentNode without the value
parentNode.AppendChild(mainNode);
parentNode.AppendChild(descNode);
parentNode.AppendChild(activeNode);

// save the value of the fields into the nodes
mainNode.AppendChild(categoryText);
descNode.AppendChild(descText);
activeNode.AppendChild(activeText);

xmlDoc.Save(Server.MapPath("categories.xml"));

and in vb.net

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

Dim root As XmlNode = xmlDoc.DocumentElement
Dim ListNode As XmlElement = xmlDoc.CreateElement("CategoryList")

Dim childNode As XmlElement = xmlDoc.CreateElement("MainCategory")
Dim parentNode As XmlElement = xmlDoc.CreateElement("Category")
parentNode.SetAttribute("ID", "04")
xmlDoc.DocumentElement.PrependChild(parentNode)
' Set attribute name and value!

Dim mainNode As XmlElement = xmlDoc.CreateElement("MainCategory")
Dim descNode As XmlElement = xmlDoc.CreateElement("Description")
Dim activeNode As XmlElement = xmlDoc.CreateElement("Active")

' retrieve the text
Dim categoryText As XmlText = xmlDoc.CreateTextNode(txt_maincategory.Text)
Dim descText As XmlText = xmlDoc.CreateTextNode(txt_description.Text)
Dim activeText As XmlText = xmlDoc.CreateTextNode(txt_active.Text)

' append the nodes to the parentNode without the value
parentNode.AppendChild(mainNode)
parentNode.AppendChild(descNode)
parentNode.AppendChild(activeNode)

' save the value of the fields into the nodes
mainNode.AppendChild(categoryText)
descNode.AppendChild(descText)
activeNode.AppendChild(activeText)

xmlDoc.Save(Server.MapPath("categories.xml"))

No comments:

Post a Comment