problem parsing with XMLReader (using ReadSubTree)

Posted by no9 on Stack Overflow See other posts from Stack Overflow or by no9
Published on 2010-04-29T10:40:59Z Indexed on 2010/04/29 10:47 UTC
Read the original article Hit count: 385

Filed under:
|
|

Hello.

Im trying to build a simple XML to Controls parser in my CF application. In the code below the string im trying to parse looks like this:

"<Panel><Label>Text1</Label><Label>Text2</Label></Panel>"

The result i want with this code would be a Panel with two labels. But the problem is when the first Label is parsed the subreader.Read() returns false in the ParsePanelElementh method, and so it falls out of while statement. Since im new into XMLReader i must be missing something very simple. Any help would be apreciated !

peace.

static class XMLParser
{
    public static Control Parse(string aXmlString)
    {
        XmlReader reader = XmlReader.Create(new StringReader(aXmlString));
        return ParseXML(reader);
    }

    public static Control ParseXML(XmlReader reader)
    {
        using (reader)
        {
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    if (reader.LocalName == "Panel")
                    {
                        return ParsePanelElement(reader);
                    }

                    if (reader.LocalName == "Label")
                    {
                        return ParseLabelElement(reader);
                    }
                }
            }
        }
        return null;
    }

    private static Control ParsePanelElement(XmlReader reader)
    {
        var myPanel = new Panel();
        XmlReader subReader = reader.ReadSubtree();
        while (subReader.Read())
        {
            Control subControl = ParseXML(subReader);
            if (subControl != null)
            {
                myPanel.Controls.Add(subControl);
            };
        }
        return myPanel;
    }

    private static Control ParseLabelElement(XmlReader reader)
    {
        reader.Read();
        var myString = reader.Value as string;
        var myLabel = new Label();
        myLabel.Text = myString;
        return myLabel;
    }
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about compact-framework