Thursday 9 June 2011

XML - Reading from an XML Document.

Finally how to read from a XML Document, with this little script for a page.

use the following for c#

protected void Page_Load(object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
DataSet mycountries = new DataSet();
mycountries.ReadXml(MapPath("text_xml.xml"));

rb.DataSource = mycountries;
rb.DataValueField = "value";
rb.DataTextField = "design";
rb.DataBind();

xmlDoc.Load(MapPath("text_xml.xml"));

XmlNodeList xmlnodelist = xmlDoc.DocumentElement.ChildNodes;
XmlNode xmlnode = xmlnodelist.Item(0);
int xmlcount = xmlnodelist.Count;

TextBox1.Text = xmlnode["design"].InnerText;
TextBox2.Text = xmlnode["value"].InnerText;

Body.Style.Add("background-color", xmlnode["backcolor"].InnerText);
XmlNode xmlnode2 = xmlnodelist.Item(1);
TextBox2.Text = xmlnode2["value"].InnerText;

}
protected void Button1_Click(object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(MapPath("text_xml.xml"));
XmlNodeList xmlnodelist2 = xmlDoc.DocumentElement.ChildNodes;
XmlNode xmlnode2 = xmlnodelist2.Item(1);
TextBox1.Text = xmlnode2["design"].InnerText;
Body.Style.Add("background-color", xmlnode2["backcolor"].InnerText);
Body.Style.Add("color", "white");

}



or in vb.net use:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim xmlDoc As New XmlDocument


Dim mycountries = New DataSet
mycountries.ReadXml(MapPath("text_xml.xml"))

rb.DataSource = mycountries
rb.DataValueField = "value"
rb.DataTextField = "design"
rb.DataBind()

xmlDoc.Load(MapPath("text_xml.xml"))

Dim xmlnodelist As XmlNodeList = xmldoc.DocumentElement.ChildNodes
Dim xmlnode As XmlNode = xmlnodelist.Item(0)
TextBox1.Text = xmlnode("design").InnerText
TextBox2.Text = xmlnode("value").InnerText

Body.Style.Add("background-color", xmlnode("backcolor").InnerText)
Dim xmlnode2 As XmlNode = xmlnodelist.Item(1)
TextBox2.Text = xmlnode2("value").InnerText

End Sub

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim xmlDoc As New XmlDocument
xmlDoc.Load(MapPath("text_xml.xml"))
Dim xmlnodelist2 As XmlNodeList = xmlDoc.DocumentElement.ChildNodes
Dim xmlnode2 As XmlNode = XmlNodeList2.Item(1)
TextBox1.Text = xmlnode2("design").InnerText
Body.Style.Add("background-color", xmlnode2("backcolor").InnerText)
Body.Style.Add("color", "white")
End Sub

XML - Delete All Elements in XML Document

The penultamite one today in my tips is how to delete all elements in a XML Document

in c# use:

string filename = "categories.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Server.MapPath(filename));
XmlNode root = xmlDoc.DocumentElement;
XmlNodeList nodes = xmlDoc.SelectNodes("//Category");
foreach (XmlNode node in nodes)
{
node.ParentNode.RemoveChild(node);
}
xmlDoc.Save(Server.MapPath(filename));

and in vb.net use:

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

Dim root As XmlNode = xmlDoc.DocumentElement
Dim nodes As XmlNodeList = xmlDoc.SelectNodes("//Category")

For Each node As XmlNode In nodes
node.ParentNode.RemoveChild(node)
Next
xmlDoc.Save(Server.MapPath(filename))

XML - Delete an element by the ID

Next step is to delete an element by its ID:

in c# use

string filename = "categories.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Server.MapPath(filename));
XmlNode root = xmlDoc.DocumentElement;
XmlNodeList nodes = xmlDoc.SelectNodes("/CategoryList/Category[@ID='03']");
foreach (XmlNode node in nodes)
{
node.ParentNode.RemoveChild(node);
}
xmlDoc.Save(Server.MapPath(filename));

and in vb.net use:

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

Dim root As XmlNode = xmlDoc.DocumentElement
Dim nodes As XmlNodeList = xmlDoc.SelectNodes("/CategoryList/Category[@ID='03']")
For Each node As XmlNode In nodes
node.ParentNode.RemoveChild(node)
Next
xmlDoc.Save(Server.MapPath(filename))

XML - Finding a XML Element by the attribute ID

Straight as it sounds, its now time to demonstrate how to find an element by the element's attribute ID.

in c#

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

XmlNodeList xnList = xmlDoc.SelectNodes("/CategoryList/Category[@ID='02']");
foreach (XmlNode xn in xnList)
{
Console.WriteLine(xn.InnerText);
}


and in vb.net

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

Dim xnList As XmlNodeList = xmlDoc.SelectNodes("/CategoryList/Category[@ID='01']")


For Each xn As XmlNode In xnList
MsgBox(xn.InnerText)
Next

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))

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"))

XML - Create New XML Document

The time of year at looking how XML interacts with c#/vb.net is upon us and its time to start to look at the coding.

Now firstly remember to copy these Namespaces at the top of the page where you will write your code.

For c# paste in:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Data;


and vb.net paste in:

Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Xml
Imports System.Data


Now for the code for creating that new XML document from c#/vb.net code:

For c# use the following:

XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
// Create the root element
XmlElement rootNode = xmlDoc.CreateElement("CategoryList");
xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement);
xmlDoc.AppendChild(rootNode);

// Create a new element and add it to the root node
XmlElement parentNode = xmlDoc.CreateElement("Category");

// Set attribute name and value!
parentNode.SetAttribute("ID", "01");

xmlDoc.DocumentElement.PrependChild(parentNode);

// Create the required nodes
XmlElement mainNode = xmlDoc.CreateElement("MainCategory");
XmlElement descNode = xmlDoc.CreateElement("Description");
XmlElement activeNode = xmlDoc.CreateElement("Active");

// retrieve the text
XmlText categoryText = xmlDoc.CreateTextNode("XML");
XmlText descText = xmlDoc.CreateTextNode("This is a list my XML articles.");
XmlText activeText = xmlDoc.CreateTextNode("true");

// 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 use:

Sub create_and_save()

Dim xmlDoc As XmlDocument = New XmlDocument
Dim xmlDeclaration As XmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "")
Dim rootNode As XmlElement = xmlDoc.CreateElement("CategoryList")
xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement)
xmlDoc.AppendChild(rootNode)

'Create a new element and add it to the root node
Dim parentNode As XmlElement = xmlDoc.CreateElement("Category")

'Set attribute name and value!
parentNode.SetAttribute("ID", "01")
xmlDoc.DocumentElement.PrependChild(parentNode)

'Create the required nodes
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("XML")
Dim descText As XmlText = xmlDoc.CreateTextNode("This is a list my XML articles.")
Dim activeText As XmlText = xmlDoc.CreateTextNode("true")

'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"))

End Sub