logo

Parse XML into Treeview

logo
Parse XML into Treeview

Where I currently work, there are a lot of *nix based systems that write logs to a log file on the hard drive and they are recorded in XML format. When looking for your problem or issue based off certain information and are trying to troubleshoot, it can be very hard to look through all those lines through a terminal screen. I made a tool that will allow you to copy several lines of the log into a text box and it will create a tab with a tree-view control on each tab and automatically parse each line from the log into it’s own tree-view. This has made supporting these things a little easier and it wasn’t that hard to achieve. Let’s take a look at the bulk of the program. On the form, there is a text box, a button, and a tab view.

        private void cmdParse_Click(object sender, EventArgs e)
        {
            if (txtInput.Text != String.Empty)
            {
                tvXMLView.ResetText();
                FillTree(tvXMLView);
            }
        }

This is just called when the user clicks a button and makes sure the text box is not empty. We are going to omit the code about adding the tab and tree view to the form, so the next step is to run the FillTree function.

        private void FillTree(TreeView currenttree)
        {
            try
            {
                XmlDocument dom = new XmlDocument();
                dom.LoadXml(txtInput.Text);
                currenttree.Nodes.Clear();
                currenttree.Nodes.Add(new TreeNode(dom.DocumentElement.Name));
                TreeNode tNode = new TreeNode();
                tNode = currenttree.Nodes[0];
                AddNode(dom.DocumentElement, tNode);
            }
            catch (XmlException xmlex)
            {
                MessageBox.Show("XML Malformed. Reason for Error: - " + xmlex.Message, "Error");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Non XML Error Occured: " + ex.Message, "Error");
            }
        }
 

First we create an XmlDocument that we can use to read through the XML in the text box. Next we ensure the tree view is empty and we are not going to append more data to an already parsed tree view. Then we begin to iterate through the values and processing them through the AddNode function.

        private void AddNode(XmlNode inXmlNode, TreeNode inTreeNode)
        {
            string strCheck;
            XmlNode xNode;
            TreeNode tNode;
            XmlNodeList nodeList;
            int intLength;
            int intStart;
            int intEnd;
            int i = 0;
            if (inXmlNode.HasChildNodes)
            {
                nodeList = inXmlNode.ChildNodes;
                for (i = 0; i <= nodeList.Count - 1; i++)
                {
                    xNode = inXmlNode.ChildNodes[i];
                    inTreeNode.Nodes.Add(new TreeNode(xNode.Name));
                    tNode = inTreeNode.Nodes[(int)i];
                    AddNode(xNode, tNode);
                }
            }
            else
            {
                if ((inXmlNode.OuterXml).Trim().Contains("></"))
                {
                    strCheck = (inXmlNode.OuterXml).Trim();
                    intStart = 1;
                    intEnd = strCheck.IndexOf("></") + 3;
                    intLength = strCheck.Length - intEnd;
                    strCheck = strCheck.Substring(intStart, intLength - 1);
                    inTreeNode.Text = strCheck;
                }
                else
                {
                    strCheck = inXmlNode.OuterXml.Trim();
                    inTreeNode.Text = strCheck;
                }
            }
            tvXMLView.ExpandAll();
        }

As you can see, we are passing the node we are currently running and the tree view we are currently using. We check for it to contain children (indicating a parent node) and if it does, we create that node and then call the same function to go down through until we reach the child. Once the child is reached, we post the value of the child to the bottom node and then work back through. I also added a little bit of code to parse out the open and close brackets for the items in the event there is no value for that node. That about does it. That is all it takes. It can take this XML (found on Microsoft’s website as an XML sample) and parse it into a tree view.

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications
      with XML.</description>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world.</description>
   </book>
   <book id="bk103">
      <author>Corets, Eva</author>
      <title>Maeve Ascendant</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-11-17</publish_date>
      <description>After the collapse of a nanotechnology
      society in England, the young survivors lay the
      foundation for a new society.</description>
   </book>
   <book id="bk104">
      <author>Corets, Eva</author>
      <title>Oberon's Legacy</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2001-03-10</publish_date>
      <description>In post-apocalypse England, the mysterious
      agent known only as Oberon helps to create a new life
      for the inhabitants of London. Sequel to Maeve
      Ascendant.</description>
   </book>
   <book id="bk105">
      <author>Corets, Eva</author>
      <title>The Sundered Grail</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2001-09-10</publish_date>
      <description>The two daughters of Maeve, half-sisters,
      battle one another for control of England. Sequel to
      Oberon's Legacy.</description>
   </book>
   <book id="bk106">
      <author>Randall, Cynthia</author>
      <title>Lover Birds</title>
      <genre>Romance</genre>
      <price>4.95</price>
      <publish_date>2000-09-02</publish_date>
      <description>When Carla meets Paul at an ornithology
      conference, tempers fly as feathers get ruffled.</description>
   </book>
   <book id="bk107">
      <author>Thurman, Paula</author>
      <title>Splish Splash</title>
      <genre>Romance</genre>
      <price>4.95</price>
      <publish_date>2000-11-02</publish_date>
      <description>A deep sea diver finds true love twenty
      thousand leagues beneath the sea.</description>
   </book>
   <book id="bk108">
      <author>Knorr, Stefan</author>
      <title>Creepy Crawlies</title>
      <genre>Horror</genre>
      <price>4.95</price>
      <publish_date>2000-12-06</publish_date>
      <description>An anthology of horror stories about roaches,
      centipedes, scorpions  and other insects.</description>
   </book>
   <book id="bk109">
      <author>Kress, Peter</author>
      <title>Paradox Lost</title>
      <genre>Science Fiction</genre>
      <price>6.95</price>
      <publish_date>2000-11-02</publish_date>
      <description>After an inadvertant trip through a Heisenberg
      Uncertainty Device, James Salway discovers the problems
      of being quantum.</description>
   </book>
   <book id="bk110">
      <author>O'Brien, Tim</author>
      <title>Microsoft .NET: The Programming Bible</title>
      <genre>Computer</genre>
      <price>36.95</price>
      <publish_date>2000-12-09</publish_date>
      <description>Microsoft's .NET initiative is explored in
      detail in this deep programmer's reference.</description>
   </book>
   <book id="bk111">
      <author>O'Brien, Tim</author>
      <title>MSXML3: A Comprehensive Guide</title>
      <genre>Computer</genre>
      <price>36.95</price>
      <publish_date>2000-12-01</publish_date>
      <description>The Microsoft MSXML3 parser is covered in
      detail, with attention to XML DOM interfaces, XSLT processing,
      SAX and more.</description>
   </book>
   <book id="bk112">
      <author>Galos, Mike</author>
      <title>Visual Studio 7: A Comprehensive Guide</title>
      <genre>Computer</genre>
      <price>49.95</price>
      <publish_date>2001-04-16</publish_date>
      <description>Microsoft Visual Studio 7 is explored in depth,
      looking at how Visual Basic, Visual C++, C#, and ASP+ are
      integrated into a comprehensive development
      environment.</description>
   </book>
</catalog>

Viola!

xml_parser

Note - I made the above form just for the purpose of this post

This simple tool has made a world of difference at work and everyone that supports the systems now uses it. I also made it so that you can right-click on the value and copy it to your clipboard so that you can have it without typing it as some of the values we are looking for can be long hexadecimal values. Then I added some preferences through a control panel that updates the registry and made this a full-featured tool. That concludes this post. Thanks for reading.

Leave a Reply

logo
logo
| Powered by Wordpress |