LINQ读取XML到列表为未知节点提供对象引用



我有一个XML队列,它们通过linq读取,如下所示:示例XML

[XML Link](http://www.hattem.nl/roonline/0269/plannen/NL.IMRO.0269.OV165-/NL.IMRO.0269.OV165-VG01/g_NL.IMRO.0269.OV165-VG01.xml)

C#代码

    List<String> PlanInfo = new List<string>();
    XDocument xdoc = null;
    XNamespace ns = null;
    try
    {
        //List<String> PlanValuesList = new List<string>();
        xdoc = XDocument.Load(gLink);
        ns = xdoc.Root.Name.Namespace;
        var test = (
            from planInfo in xdoc.Descendants(ns + "Plan").Descendants(ns + "Eigenschappen")
            from Onderdelen in xdoc.Descendants(ns + "Onderdelen")
            select new
            {
                Naam = (string)planInfo.Element(ns + "Naam").Value ?? string.Empty,
                Type = (string)planInfo.Element(ns + "Type").Value ?? string.Empty,
                Status = (string)planInfo.Element(ns + "Status").Value ?? string.Empty,
                Datum = (Convert.ToString(planInfo.Element(ns + "Datum").Value).IndexOf("T") > 0) ? (string)planInfo.Element(ns + "Datum").Value.Substring(0, Convert.ToString(planInfo.Element(ns + "Datum").Value).IndexOf("T")) : (string)planInfo.Element(ns + "Datum").Value ?? string.Empty,
                Versie = (string)(planInfo.Element("VersieIMRO") ?? planInfo.Element("VersieGML")) ?? string.Empty,//Convert.ToString(planInfo.Element(ns + "VersieIMRO").Value) ?? String.Empty,
                VersiePraktijkRichtlijn = (string)planInfo.Element(ns + "VersiePraktijkRichtlijn").Value ?? string.Empty,
                BasisURL = (string)Onderdelen.Attribute("BasisURL")
            }).ToList();
        foreach (var item in test)
        {
            PlanInfo.Add(item.Naam);
            PlanInfo.Add(item.Type);
            PlanInfo.Add(item.Status);
            PlanInfo.Add(item.Datum);
            PlanInfo.Add(item.Versie);
            PlanInfo.Add(item.VersiePraktijkRichtlijn);
            PlanInfo.Add(item.BasisURL);
        }
 }
    catch (Exception ex)
    {
        //Error reading GeleideFormulier link for the plan and manifest
        throw;//Just throwing error here, as it is catched in the called method.
    }
    return PlanInfo;

在一些XML文件中,"versieIMRO"标记变为"versieGML",这会导致错误,因为对象引用未设置为对象的实例。

请告诉我如何检查是否有"versieGML"标签而不是"versieIMRO"?或者,如果其他XML中的标记名不同,该如何处理?

您希望将XElement强制转换为字符串(而不是已经是string类型的XElement.Value属性),以避免在找不到元素时出现NRE:

Version = (string)x.Element("version"),

如果您想在找不到version元素的情况下使用versionX,请尝试以下方式:

Version = (string)(x.Element("version") ?? x.Element("versionX")),

再次强调,将Value属性强制转换为string是无用的,没有任何区别。如果要获得string.Empty而不是null,请再次使用空合并运算符:

Version = (string)(x.Element("version") ?? x.Element("versionX")) ?? string.Empty,

最新更新