Home > Articles > Web Services > XML

Creating a Tree View of XML Data in Visual Studio .NET

  • Print
  • + Share This
John Mueller shows how a tree view of your XML data can help you display the details with greater ease and examine those details with greater clarity.
Like this article? We recommend

XML provides a convenient means for storing data, no matter what form the data takes. It relies on a hierarchical structure to store the data, unlike the tables used in a relational database. Consequently, XML has advantages and disadvantages versus the relational model you're probably used to using. For example, one advantage is that you don't have to worry about unnecessary data repetition, because XML structures the data as it appears in the real world. However, a big disadvantage of the XML approach is how to display the data onscreen. A hierarchical data store is hardly easy to show. Fortunately, the tree view control provided with Visual Studio .NET makes displaying XML data a lot easier.

Considering the XML

The XML file for this example is relatively simple. However, it's also representative of many XML documents seen today. It contains a combination of attributes and values. The elements stop at various levels and might not have a value. I made one concession to make the example a lot easier to demonstrate—each element includes a Parent attribute that defines a parent. However, you don't have to include such an attribute; you can simply use the level of the hierarchy as the determining factor. Listing 1 shows the XML for this example.

Listing 1 Sample XML

<?xml version="1.0" encoding="utf-8" ?>
  <Fruit Parent="0">
   <Apples Parent="Fruit">
     <Macintosh Parent="Apples">
     <Delicious Parent="Apples">
     <Courtland Parent="Apples">
   <Pears Parent="Fruit">
  <Vegetables Parent="0">
   <Carrots Parent="Vegetables">
   <Squash Parent="Vegetables">
     <Acorn Parent="Squash">
     <Zucchini Parent="Squash">
      <Yellow Parent="Zucchini">
      <Green Parent="Zucchini">

The XML isn't all that complex, but it contains enough variation that the parsing code will have to be fairly flexible. For example, the Pears node doesn't contain any children or a value—some applications would choke on a node like this one. Some of the entries are two levels deep; others have three or even four levels. Again, this adds a level of complexity to the parsing code that you might have a hard time coding without some of the features that the .NET Framework provides.

  • + Share This
  • 🔖 Save To Your Account