【问题标题】:Simple XML parsing throws Object reference error简单的 XML 解析引发对象引用错误
【发布时间】:2013-11-27 18:46:52
【问题描述】:

如何解析以下 XML 文件?

<Website.com xmlns="">
  <Matc>
    <Id>1</Id>
    <Date>2013-11-27T18:00:00+01:00</Date>
    <Home>Moscow</Home>
  </Matc>
  <Matc>
    <Id>2</Id>
  </Matc>
</Website.com>

我尝试了以下代码,但由于 XML 文件的第二部分缺少 [Date]Home,因此引发了 Object reference not set to an instance of an object 错误。

 Dim ns As XNamespace = ""
 Dim matcFromXml = From m In xDoc.Descendants("Matc") Select New With { _
   .Id = IIf(m.Element(ns + "Id") Is Nothing, 0, m.Descendants(ns + "Id").FirstOrDefault().Value), _
   .[Date] = IIf(m.Element(ns + "Date") Is Nothing, DateTime.Now, UtcToDateTime(m.Descendants(ns + "Date").FirstOrDefault().Value)), _
   .Home = IIf(m.Element(ns + "Home") Is Nothing, "", m.Descendants(ns + "Home").FirstOrDefault().Value)}

我该如何解决这个问题?我在这里做错了什么?

【问题讨论】:

    标签: xml vb.net linq linq-to-xml


    【解决方案1】:

    强烈建议将XElement 转换为IntegerDateTime?,而不是读取Value 属性,正是出于这个原因。另外,请考虑使用 If 合并运算符。

    Dim matcFromXml = From m In xDoc.Descendants("Matc") Select New With { _
        .Id = CInt(m.Descendants(ns + "Id").FirstOrDefault()),
        .[Date] = If(CType(m.Descendants(ns + "Date").FirstOrDefault(), Date?), DateTime.Now),
        .Home = If(CStr(m.Descendants(ns + "Home").FirstOrDefault()),"")}
    

    如果没有Id 元素,那么使用普通的CInt 作为Id 将导致错误。而是使用IfCType

        .Id = If(CType(m.Descendants(ns + "Id").FirstOrDefault(),Integer?),0),
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多