Recipe 14.22. Reading XML into a TreeView


Problem

You have some XML content in a file. You want to display it using a TReeView control, so that you can expand specific branches.

Solution

Sample code folder: Chapter 14\XMLTreeView

There are many ways to go about this task, but one of the most straightforward is to load the content into an XmlDocument object, then traverse this object's attributes and nodes. This recipe's code loads an XML file into a TReeView control.

Discussion

Create a new Windows Forms application, and add the following controls to Form1:

  • A TextBox control named XMLFile.

  • A Button control named LoadFile. Set its Text property to Load.

  • A TReeView control named XMLTree.

Add informational labels if desired, and arrange the controls so that Form1 looks like the form in Figure 14-17.

Figure 14-17. Controls on the XML-to-TreeView sample


Now add the following source code to Form1's class template:

 Private Sub LoadFile_Click(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles LoadFile.Click    ' ----- Load an   XML file into the form's TreeView control.    Dim fileContent As   Xml.XmlDocument    ' ----- Make sure the file exists.    If (My.Computer.FileSystem.FileExists(XMLFile.Text) = _          False) Then       MsgBox("Please supply a valid file name.")       Return    End If    ' ----- Load the XML content into an XMLDocument object.    Try       fileContent = New Xml.XmlDocument       fileContent.Load(XMLFile.Text)    Catch ex As Exception       MsgBox("The XML file could not be loaded due to " & _          "the following error:" & vbCrLf & vbCrLf & _          ex.Message)       fileContent = Nothing       Return    End Try    ' ----- Remove any existing content in the TreeView.    XMLTree.Nodes.Clear( )    ' ----- Call a recursive method that will scan down    '       all branches of the XML file.    For Each oneNode As Xml.XmlNode In fileContent.ChildNodes       AddNodeToTree(oneNode, Nothing)    Next oneNode End Sub Private Sub AddNodeToTree(ByVal oneNode As Xml.XmlNode, _       ByVal fromNode As TreeNode)    ' ----- Add a node and all of its subordinate items.    Dim baseNode As TreeNode    ' ----- Ignore plain text nodes, as they are picked up    '       by the inner-text code below.    If (oneNode.NodeType = Xml.XmlNodeType.Text) Then Return    ' ----- Treat the "<?xml…" node specially.    If (oneNode.NodeType = Xml.XmlNodeType.XmlDeclaration) _          And (fromNode Is Nothing) Then       baseNode = XMLTree.Nodes.Add( _          oneNode.OuterXml.ToString( ))       Return    End If    ' ----- Add the node itself.    If (fromNode Is Nothing) Then       baseNode =   XMLTree.Nodes.Add(oneNode.Name)    Else       baseNode = fromNode.Nodes.Add(oneNode.Name)    End If    ' ----- Add the attributes.    If (oneNode.Attributes IsNot Nothing) Then       For Each oneAttr As   Xml.XmlAttribute In _             oneNode.Attributes          baseNode.Nodes.Add("Attribute: " & oneAttr.Name & _             " = """ & oneAttr.Value & """")       Next oneAttr    End If    ' ----- Add content if available.    If (oneNode.InnerText <> "") Then       baseNode.Nodes.Add("Content: " & oneNode.InnerText)    End If    ' ----- Add the child nodes.    If (oneNode.ChildNodes IsNot Nothing) Then       For Each subNode As Xml.XmlNode In oneNode.ChildNodes          AddNodeToTree(subNode, baseNode)       Next subNode    End If End Sub 

To run the program, type a valid XML filename in the XMLFile field, and then click the Load button. The XML content appears in the treeView control, with branches collapsed. This program was run using this recipe's .vbproj file for the input (it's an XML file). Figure 14-18 shows the results.

Figure 14-18. XML displayed as a TreeView


The TreeView control is designed to present hierarchical data, which is precisely what you find in XML content. The System.Xml.XmlDocument object represents the content of XML data by parsing the raw XML text and building distinct Xml.XmlNode objects for each element and branch point within the content. Both XmlDocument and XmlNode include a ChildNodes collection that provides access to the XML tags found immediately within the current tag. These objects also include an Attributes collection that lists the name and value of each tag attribute.

See Also

Recipes 14.23 and 14.24 discuss other methods of working with XML content.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net