【发布时间】:2020-09-25 07:21:28
【问题描述】:
我正在尝试解析大小约为 400KB 的 XML 文件。但我无法克服堆栈溢出异常。首先,我创建 XmlReader 并将其传递给 XML 文件。然后我从 XmlReader 创建 XElement。
这是我的代码:
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;
}
【问题讨论】:
-
你真的不需要
ParseToView- 它不会解析任何东西,它只会将一种类型的类转换为另一种类型。由于您已经使用 LINQ-to-XML,您可以使用 LINQ 从 XElement 数据生成 ViewModel 类。或者您可以直接绑定到数据。毕竟,ViewContent 和 ElementAttribute 包含解析类所做的相同事情。为什么要复制数据?
标签: c# xml parsing stack-overflow