Creating a Tree View of XML Data in Visual Studio .NET
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 demonstrateeach 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" ?> <Categories> <Fruit Parent="0"> <Apples Parent="Fruit"> <Macintosh Parent="Apples"> 100 </Macintosh> <Delicious Parent="Apples"> 150 </Delicious> <Courtland Parent="Apples"> 75 </Courtland> </Apples> <Pears Parent="Fruit"> </Pears> </Fruit> <Vegetables Parent="0"> <Carrots Parent="Vegetables"> 125 </Carrots> <Squash Parent="Vegetables"> <Acorn Parent="Squash"> 75 </Acorn> <Zucchini Parent="Squash"> <Yellow Parent="Zucchini"> 175 </Yellow> <Green Parent="Zucchini"> 180 </Green> </Zucchini> </Squash> </Vegetables> </Categories>
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 valuesome 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.