I'm trying to parse an XML file of size around 400KB. But I cannot overcome the stack overflow exception. First I create XmlReader and pass it to the XML file. Then I create XElement from the XmlReader.
This is my code:
private ViewContent ParseToView(XElement xElement)
{
ViewContent viewContent = new ViewContent();
viewContent.elementName = xElement.Name.LocalName;
foreach (XAttribute item in xElement.Attributes())
{
viewContent.attributes.Add(new ElementAttribute(item.Name.ToString(), item.Value));
}
foreach (XElement item in xElement.Elements())
{
viewContent.viewContents.Add(ParseToView(xElement));
}
return new ViewContent();
}
}
public class ViewContent
{
public string elementName;
public List<ElementAttribute> attributes = new List<ElementAttribute>();
public List<ViewContent> viewContents = new List<ViewContent>();
}
public class ElementAttribute
{
public ElementAttribute(string attributeName, string attributeValue)
{
this.attributeName = attributeName;
this.attributeValue = attributeValue;
}
public string attributeName;
public string attributeValue;
}
In method ParseToView
you are calling same method recursively but you're calling it with same parameter - viewContent.viewContents.Add(ParseToView(xElement));
- this causes stackoverflow:
viewContent.viewContents.Add(ParseToView(xElement));
should have probably been:
viewContent.viewContents.Add(ParseToView(item));
in method:
private ViewContent ParseToView(XElement xElement)
{
ViewContent viewContent = new ViewContent();
viewContent.elementName = xElement.Name.LocalName;
foreach (XAttribute item in xElement.Attributes())
{
viewContent.attributes.Add(new ElementAttribute(item.Name.ToString(), item.Value));
}
foreach (XElement item in xElement.Elements())
{
viewContent.viewContents.Add(ParseToView(xElement)); // <-Faulty line here
}
return new ViewContent();
}
}