problem parsing with XMLReader (using ReadSubTree)
- by no9
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;
}
}