views:

472

answers:

2

I have an XML file such as the one shown below

<root>
  <child1>
    <grandchild1>
       <greatgrandchild1>
       </greatgrandchild1>
       <greatgrandchild2>
       </greatgrandchild2>
       ...
    </grandchild1>
    <grandchild2>
    </grandchild2>
    <grandchild3>
    </grandchild3>
    ...
  </child1>
  <child2>
    <grandchild1>
    </grandchild1>
    <grandchild2>
    </grandchild2>
    <grandchild3>
    </grandchild3>
    ...
  </child2>
  <child3>
    <grandchild1>
    </grandchild1>
    <grandchild2>
    </grandchild2>
    <grandchild3>
    </grandchild3>
    ...
  </child3>
  ...
</root>

Each child node has a different name. I need to display this XML in the following manner:

Each child node is displayed as an Expander. All the grandchildren of that child node is placed inside that expander. Each grandchild and its children should be grouped and should have a background color. The next grandchild and its children should have an alternate color background.

The whole data has two columns. So the control that is chosen to display this data should be able to support multiple columns.

I was thinking of a DataGrid. But I cannot use its built in features as I cannot do data binding. I need to programmatically add the items to the DataGrid. Please let me know how can I solve this problem. Any help is greatly appreciated. Thanks in advance.

A: 

This really isn't XML. Each element is a different type because each is named differently. Is there no way to get your data into correctly formatted XML? For example:

<root>
  <child name="name1">
    <grandchild name="name11">
      <greatgrandchild name="name111"/>
      <greatgrandchild name="name112"/>
    </grandchild>
    <grandchild name="name12"/>
  </child>
  <child name="name2">
    <grandchild name="name21"/>
    <grandchild name="name22"/>
  </child>
</root>

Notice how this is a series of elements of the same type with attributes and child elements. There's a good set of xml tutorials at w3schools. com.

If you could get your data into some correct XML, you could probably display the data as you wish very easily. You could use xml data providers and bind to the xml directly, you could use xml serialization to easily load your data into a series of objects and collections, you could load this into an XmlDocument and manipulate it that way too. If you're writing this xml yourself, then you'd probably spend less time reformatting the data than trying to find a way to stick your weird xml into your program.

After you fix your xml, here's another post of a similar question http://stackoverflow.com/questions/1383817/c-wpf-fill-datagrid-or-listview-from-xml-file.

Benny Jobigan
+1  A: 

Once your XML is cleaned up as noted by Ben - the easiest method I have found for dealing with hierarchical XML data is to load it into a DataSet object (DataSet.ReadXML()).

Then you can bind the DataSet and the specific DataTable you want to your grid control.

Ron Savage