XML Document Sample
Sample of how to use to the XML Document class in C#.private StringBuilder m_sbXmlInfo = new StringBuilder();
private void XmlDemo(string sFileName)
{
// create an instance of the XML Document
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
// load up the XML file into our XML document
xmlDoc.Load(sFileName);
//string sTemp = null;
// get the root node
System.Xml.XmlElement nodeRoot = xmlDoc.DocumentElement;
this.m_sbXmlInfo.Length = 0;
if (nodeRoot == null)
{
this.m_sbXmlInfo.Append("Source document is empty");
}
else if (nodeRoot.HasChildNodes)
{
this.m_sbXmlInfo.AppendFormat("Root node name: {0}", nodeRoot.Name);
// get a specific node off of the root node
var specificNode = nodeRoot["Person"];
// iterate through each of the child nodes off the root node.
foreach(System.Xml.XmlNode node in nodeRoot.ChildNodes)
{
this.DoNodeInspection(node, 1);
}
}
}
private void DoNodeInspection(System.Xml.XmlNode node, int lLevelsDeep)
{
if (node == null)
{
// if null, get out now.
return;
}
// determine if the node has children
if (node.HasChildNodes)
{
// add a new line
this.m_sbXmlInfo.AppendLine();
// add some spaces
this.m_sbXmlInfo.Append(string.Empty.PadLeft(lLevelsDeep * 2));
// add the node name.
this.m_sbXmlInfo.AppendFormat("Node Name: {0}", node.Name);
// this node has child nodes.
foreach (System.Xml.XmlNode node2 in node.ChildNodes)
{
this.DoNodeInspection(node2, lLevelsDeep + 1);
}
}
else
{
// no child nodes
this.m_sbXmlInfo.AppendLine(); // add a new line
// add some spaces
this.m_sbXmlInfo.Append(string.Empty.PadLeft(lLevelsDeep * 2));
// output our node value.
this.m_sbXmlInfo.AppendFormat("Node Value: {0}", node.Value);
}
}
Last modified by Mohit @ 4/7/2025 7:33:17 PM