Introduction
This article contains an illustration of displaying XML element values into a TreeView control 's items. We use the class TreeViewItem to represent each node in the tree. The class TreeView and class TreeViewItem are in the System.Windows.Controls namespace. TreeViewItems are added to the TreeView to emphasize the structure of the XML document.
The C# program demonstrates how to manipulate a DOM tree programmatically to display it graphically in a TreeView control. The GUI for this application contains a TreeView control named xmlTreeView. The application loads letter.xml into XmlReader, then displays the document's tree structure in theTreeView control.
XML File
<?xml version = "1.0"?>
<!-- letter.xml -->
<!-- Business letter formatted with XML -->
<letter>
<contact type = "sender">
<name>Kailash</name>
<address1>Box 12345</address1>
<address2>15 Any Ave.</address2>
<city>Othertown</city>
<state>Otherstate</state>
<zip>400070</zip>
<phone>022-99999</phone>
<flag gender = "F" />
</contact>
<contact type = "receiver">
<name>Panchanan</name>
<address1>123 Main St.</address1>
<address2></address2>
<city>Anytown</city>
<state>Anystate</state>
<zip>400072</zip>
<phone>555-1234</phone>
<flag gender = "M" />
</contact>
<salutation>Dear Sir:</salutation>
<paragraph>
It is our privilege to inform you about our new database
managed with XML. This new system allows you to reduce the
load on your inventory list server by having the client machine
perform the work of sorting and filtering the data.
</paragraph>
<paragraph>
Please visit our Web site for availability
and pricing.
</paragraph>
<closing>Sincerely,</closing>
<signature>Ms. Doe</signature>
</letter>
Create an object of the class TreeviewItem in the class label and in the windows Load event handler create an XmlReaderSettings object and set its IgnoreWhitespace property to true so that the insignificant whitespace in the XML document is ignored. Then invoke the static XmlReadermethod to create, parse and load letter.xml.
public partial class XMLDataViewer : Window
{
private TreeViewItem tree; // TreeViewItem reference
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// create Xml ReaderSettings and
// set the IgnoreWhitespace property
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreWhitespace = true;
// create XmlReader object
XmlReader reader = XmlReader.Create("letter.xml", settings);
tree = new TreeViewItem(); // instantiate TreeViewItem
tree.Header = "letter.xml"; // assign name to TreeViewItem
xmlTreeView.Items.Add( tree ); // add TreeViewItem to TreeView
BuildTree( reader, tree ); // build node and tree hierarchy
}
private void BuildTree( XmlReader reader, TreeViewItem TreeViewItem )
{
// TreeViewItem to add to existing tree
TreeViewItem newNode = new TreeViewItem();
while ( reader.Read() )
{
// build tree based on node type
switch ( reader.NodeType )
{
// if Text node, add its value to tree
case XmlNodeType.Text:
newNode.Header = reader.Value;
TreeViewItem.Items.Add(newNode);
break;
case XmlNodeType.EndElement: // if EndElement, move up tree
TreeViewItem =(TreeViewItem)TreeViewItem.Parent;
break;
// if new element, add name and traverse tree
case XmlNodeType.Element:
// determine if element contains content
if ( !reader.IsEmptyElement )
{
// assign node text, add newNode as child
newNode.Header = reader.Name;
TreeViewItem.Items.Add(newNode);
// set TreeViewItem to last child
TreeViewItem = newNode;
} // end if
else // do not traverse empty elements
{
// assign NodeType string to newNode
// and add it to tree
newNode.Header = reader.NodeType.ToString();
TreeViewItem.Items.Add(newNode);
} // end else
break;
default: // all other types, display node type
newNode.Header = reader.NodeType.ToString();
TreeViewItem.Items.Add(newNode);
break;
} // end switch
newNode = new TreeViewItem();
} // end while
// update TreeView control
// xmlTreeView. // expand tree nodes in TreeView
//xmlTreeView.Refresh(); // force TreeView to update
} // end method BuildTree
The Method BuildTree receives an XmlReader for reading the XML document and a TreeViewItem referencing the current location in the tree (in other words, theTreeViewItem most recently added to the treeView control) declares the TreeViewItem reference newNode, that will be used for adding new Items to the treeView. The While loop iterates through each node in the XML document's DOM tree.
The switch statement adds a node to the treeView, based on the XmlReader's current node. When a text node is encountered, the Text property of the newTreeViewItemnew Node is assigned the current items's value and adds this TreeViewItem to TreeViewItem's node list.
The Switch statement matches an EndElement node type. This case moves up the tree to the current node's parent because the end of an element has been encountered accesses the TreeViewItem's Parent property to retrieve the node's current parent that matches the Element node types. Each non-empty Element NodeType increases the depth of the tree; thus, we assign the current reader Name to the newNode'sText property and add the newNode to TreeViewItem's node list. Assigns the newNode's reference to the TreeViewItem to ensure that TreeViewItem refers to the last child TreeViewItem in the node list. If the current Element node is an empty, we assign to the newNode's Text property the string representation of theNodeType. Next, the newNode is added to the TreeViewItem node list. The default case assigns the string representation of the node type to the newNode Text property, then adds the newNode to the TreeViewItem node list.
All Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Xml;
namespace MyRND_in_WPF
{/// <summary>/// Interaction logic for XMLDataViewer.xaml/// </summary>
public partial class XMLDataViewer : Window{private TreeViewItem tree; // TreeViewItem referencepublic XMLDataViewer()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// create Xml ReaderSettings and
// set the IgnoreWhitespace
propertyXmlReaderSettings settings = new XmlReaderSettings();settings.IgnoreWhitespace = true;// create XmlReader o
bjectXmlReader reader = XmlReader.Create("letter.xml", settings);tree = new TreeViewItem(); // instantiate TreeViewItemtree.Header = "letter.xml";
// assign name to TreeViewItem xmlTreeView.Items.Add( tree );
// add TreeViewItem to TreeView BuildTree( reader, tree );
// build node and tree hierarchy
}
// construct TreeView based on DOM treeprivate void BuildTree( XmlReader reader, TreeViewItem TreeViewItem )
{
// TreeViewItem to add to existing treeTreeViewItem newNode = new TreeViewItem();
while ( reader.Read() )
{
// build tree based on node typeswitch ( reader.NodeType )
{
// if Text node, add its value to treecase XmlNodeType.Text:newNode.Header = reader.Value;
TreeViewItem.Items.Add(newNode);
break;
case XmlNodeType.EndElement: // if EndElement, move up treeTreeViewItem =(TreeViewItem)TreeViewItem.Parent;
break;
// if new element, add name and traverse treecase XmlNodeType.Element:
// determine if element contains contentif ( !reader.IsEmptyElement )
{
// assign node text, add newNode as childnewNode.Header = reader.Name;
TreeViewItem.Items.Add(newNode);
// set TreeViewItem to last childTreeViewItem = newNode;
}
// end ifelse // do not traverse empty elements
{
// assign NodeType string to newNode
// and add it to treenewNode.Header = reader.NodeType.ToString();
TreeViewItem.Items.Add(newNode);
}
// end elsebreak;default:
// all other types, display node typenewNode.Header = reader.NodeType.ToString();
TreeViewItem.Items.Add(newNode); break;
}
// end switchnewNode = new TreeViewItem();
}
// end while
}
// end method BuildTree
}
Output