Facebook Like Box

Main Menu

Parsing XML in .NET

While programming we usually encounter XML files for saving some configuration settings or any kind of strunctured data. To parse XML there are different kind of libraries available. even in .NET you can use XMLReader to parse XML files. To make things simpler I have created a wrapper function which uses XMLReader to parse the XML, and return you the  parsed XML in C# Generic Collection Object "List<Object>", and for sure it is far more easier to iterate a list rather than a raw XML string. This function also support attributes, and will provide you all attributes under each node in "Dictionary<K,V>" Object.

Following is the code of function.

private List‹Object› parseXML(string rawNodeData)
        {
            //Final List object which will contain all the XML tree
            List‹Object› parsedXML = new List‹object›();

            // Create an XmlReader
            using (XmlReader reader = XmlReader.Create(new StringReader(rawNodeData)))
            {
                //Variables to store temporary values
                string tempKey = "";
                Object tempValueObject = null;
                string tempTagName = "";

                //Represent that the given node has childs
                bool haveChildNodes = false;
                string parentNodeName = "";

                //Represent the Depth of tree
                int iDepthCount = 0;

                //Previous reference of Node
                List‹Object› previousReference = null;

                //Dictionary object to store all attributes
                Dictionary‹string, string› attribute = null;

                //Dictionary object to store temporary attributes
                Dictionary‹string, string› tempAttribute = null;

                // Parse the file and display each of the nodes.
                while (reader.Read())
                {
                    switch (reader.NodeType)
                    {
                        case XmlNodeType.Element:
                            //Element Tag started
                            iDepthCount++;

                            //Making attribute to null at start for this element
                            attribute = null;

                            //Get all attributes
                            if (reader.HasAttributes)
                            {
                                attribute = new Dictionary‹string, string›();
                                while (reader.MoveToNextAttribute())
                                {
                                    attribute.Add(reader.Name, reader.Value);
                                }
                                //Move the reader back to the element
                                reader.MoveToElement();
                            }

                            //This condition will occur if the Node has child subnodes
                            if (!tempTagName.Equals(reader.Name) && !tempTagName.Equals(""))
                            {
                                //XMLNode Object
                                XMLNode xmlSubNode = new XMLNode();
                                xmlSubNode.Name = tempTagName;
                                xmlSubNode.Value = new List‹Object›();
                                if (tempAttribute != null)
                                {
                                    xmlSubNode.Attributes = tempAttribute;
                                    tempAttribute = null;
                                    //attribute = null;
                                }

                                if (previousReference != null)
                                {
                                    haveChildNodes = true;
                                    parentNodeName = tempTagName;

                                    previousReference.Add(xmlSubNode);
                                }
                                else
                                {
                                    parsedXML.Add(xmlSubNode);
                                }

                                //Setting the previous reference
                                previousReference = (List‹Object›)xmlSubNode.Value;
                            }

                            tempTagName = reader.Name;

                            tempKey = reader.Name;

                            tempAttribute = attribute;

                            //Check here if the Element content is empty then add it right here
                            if (reader.IsEmptyElement)
                            {
                                //XMLNode Object
                                XMLNode nd = new XMLNode();
                                nd.Name = tempKey;
                                if (attribute != null)
                                {
                                    nd.Attributes = attribute;
                                    attribute = null;
                                }
                                previousReference.Add(nd);

                                iDepthCount--;
                                tempTagName = "";
                            }
                            break;
                        case XmlNodeType.Text:
                            //Text of the Element
                            tempValueObject = reader.Value;

                            //XMLNode Object
                            XMLNode node = new XMLNode();
                            node.Name = tempKey;
                            node.Value = tempValueObject;
                            if (attribute != null)
                            {
                                node.Attributes = attribute;
                                attribute = null;
                            }

                            if (previousReference != null)
                            {
                                previousReference.Add(node);
                            }
                            else
                            {
                                parsedXML.Add(node);
                            }
                            break;
                        case XmlNodeType.XmlDeclaration:
                            //In case of XML Declaration
                            break;
                        case XmlNodeType.ProcessingInstruction:
                            //In case of Processing Instruction
                            break;
                        case XmlNodeType.Comment:
                            //In case of XML Comment
                            break;
                        case XmlNodeType.EndElement:
                            ////In case of End of Element
                            iDepthCount--;
                            if (haveChildNodes && reader.Name.Equals(parentNodeName))
                            {
                                haveChildNodes = false;
                                parentNodeName = "";
                            }

                            //Move to correct position in the tree
                            for (int i = 0; i ‹ iDepthCount; i++)
                            {
                                if (!(((XMLNode)(parsedXML.ElementAt(0))).Value.GetType().ToString().Equals("System.String")))
                                {
                                    if (i == 0)
                                    {
                                        previousReference = (List‹object›)((XMLNode)(parsedXML.ElementAt(0))).Value;
                                    }
                                    else
                                    {
                                        if (!(((XMLNode)(previousReference.ElementAt(previousReference.Count - 1))).Value.GetType().ToString().Equals("System.String")))
                                        {
                                            previousReference = (List‹object›)((XMLNode)(previousReference.ElementAt(previousReference.Count - 1))).Value;
                                        }
                                    }
                                }
                            }

                            tempTagName = "";
                            break;
                    }
                }
            }

            //Returning the final object
            return parsedXML;
        }

Add comment


Security code
Refresh