我正在用 C# 编写一个 XML 解析器来提取大量(许多文件,超过 200GB 的数据)以 xml 形式存储的条目。我正在使用 Linq to XML 来解析文件并将所有信息获取到我为它们创建的对象中(14 个对象;一些对象包含包含对象列表的对象列表——这是很多数据)。
我遇到的问题是某些条目可能具有某个对象的零个或多个实例。在数据库上下文中,这没问题,但我不知道如何告诉我的程序,如果它在标签下找不到合适的对象,它应该只创建一个空/默认对象。运行程序会给我一个“序列不包含元素”错误,并且异常处理不起作用,因为程序只是在找到一个空列表而不是忽略它时退出查询。
如何处理 linq-to-xml 查询中的零个或多个案例?
有问题的对象的定义是:
<!ELEMENT prior-registration-applications (other-related-in* , prior-registration-application*)>
<!ELEMENT other-related-in (#PCDATA)>
<!ELEMENT prior-registration-application (relationship-type? , number?)>
我遇到问题的代码是这样的:
priorRegistrationApplications = (
from q in e.Elements("prior-registration-applications")
select new PriorRegistrationApplications(
(string)q.Element("other-related-in"),
(from w in q.Elements("prior-registration-application")
select new PriorRegistrationApplication(
(string)w.Element("relationship-type"),
convertToInt((string)w.Element("number")))
).ToList()
)
).First(), //end prior-applications
PriorRegistrationApplications 的对象定义是:
class PriorRegistrationApplications
{
public string other_related_in; //only one appears, regardless of number of applications it seems.
List<PriorRegistrationApplication> priorRegistrationApplications;
public PriorRegistrationApplications(string other_related_in, List<PriorRegistrationApplication> priorRegistrationApplications)
{
this.other_related_in = other_related_in;
this.priorRegistrationApplications = priorRegistrationApplications;
}
对于 PriorRegistrationApplication:
class PriorRegistrationApplication
{
public PriorRegistrationApplication() {
relationship_type = "";
number = 0;
}
public PriorRegistrationApplication(string relationship_type, int number)
{
this.relationship_type = relationship_type;
this.number = number;
}