【问题标题】:getting exception while trying to query xdocument尝试查询 xdocument 时出现异常
【发布时间】:2018-04-30 22:24:04
【问题描述】:

我正在尝试使用以下代码从具有 XML 格式的 Web 响应中提取数据 但我在这一行得到空引用异常 var status = html.Element("Status");

if (oHttpWebResponse.StatusCode.ToString().ToLower() == "ok")
    {
        string contentType = oHttpWebResponse.ContentType;
        Stream content = oHttpWebResponse.GetResponseStream();
        XDocument xDoc = new XDocument(XDocument.Load(content));
        var html = xDoc.Root.Element("html");
        var status = html.Element("Status"); // getting System.NullReferenceException here 
       var statusValue = status.Value;
        var lice = html.Element("LicenseKey").Value;

    }

我不是为什么会收到此错误,而 xml 格式看起来像这样..

<html>
<Status>
200
</Status>
<LicenseKey>
FXOZ-HTTEKG-3QYB-MP2NPQ-AC7I3C-76SX-DVN4BA-C55RMK-RV2P-O5NSOQ
</LicenseKey>
<CustomerId>
U2N3XCAV
</CustomerId>
</html>

我不知道为什么我会收到这个错误,如果有人请帮忙解决这个问题,我会非常感激..

提前谢谢..

【问题讨论】:

  • 代码看起来不错,尽管您创建/加载 xdoc 的方式很愚蠢。所以发布 exact xml,我怀疑某处有一个命名空间。

标签: c# asp.net .net wcf c#-4.0


【解决方案1】:

xDoc.Root 是此 xml 文档中的“html”标签,因此您正在此“html”标签下寻找“html”子元素,这就是它为空的原因。

【讨论】:

    【解决方案2】:

    xDoc.Root 是整个文本,因为根是 html 标记。它没有子元素。 为了根据名称获取元素,您可以运行以下代码:

    var status = xDoc.Root.Elements("Status").FirstOrDefault();
    // ensure not null is assigned to "stringValue"
    var statusValue = status==null? String.Empty: status.Value; 
    

    在 C# 6.0 之后,您也可以使用此分配来确保 null 不会分配给 stringValue

    statusValue = status?.Value ?? String.Empty;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-25
      • 2012-05-30
      • 1970-01-01
      • 1970-01-01
      • 2013-05-08
      • 1970-01-01
      • 1970-01-01
      • 2015-08-11
      相关资源
      最近更新 更多