【问题标题】:using Linq to query XDocument keeps throwing Null pointer exception使用 Linq 查询 XDocument 不断抛出 Null 指针异常
【发布时间】:2012-10-25 03:42:20
【问题描述】:

如何使用 Linq 查询 xml 文档?当我使用“where”子句下面的代码时,抛出“对象引用未设置为对象的实例。”。具体来说,我认为节点为空。请帮忙!

我的 xml 看起来像这样:

<qbo:QboCompanyPreferences xmlns="http://www.intuit.com/sb/cdm/v2" xmlns:qbp="http://www.intuit.com/sb/cdm/qbopayroll/v1" xmlns:qbo="http://www.intuit.com/sb/cdm/qbo">
  <qbo:Preference>
    <Name>TaxAccountId</Name>
    <Value>34</Value>
  </qbo:Preference>
  <qbo:Preference>
    <Name>TaxPercent</Name>
    <Value>4.5%</Value>
  </qbo:Preference>
</qbo:QboCompanyPreferences>

我正在使用这样的 XDocument:

XDocument doc = XDocument.Parse(serviceResponse);
string taxNodeName = "TaxPercent";
XNamespace qbo = "http://www.intuit.com/sb/cdm/qbo";

var Preference = (from node in doc.Descendants(qbo + "Preference")
                        where node.Element("Name").Value == taxNodeName
                        select node).FirstOrDefault();

Response.Write(Preference.ToString());

【问题讨论】:

    标签: linq-to-xml


    【解决方案1】:

    这可能已经处理了,但试试这个

    XDocument doc = XDocument.Parse(serviceResponse);
    string taxNodeName = "TaxPercent";
    XNamespace qbo = "http://www.intuit.com/sb/cdm/qbo";
    XNamespace ns = "http://www.intuit.com/sb/cdm/v2";
    
    var Preference = (from node in doc.Descendants(qbo + "Preference")
                        where node.Element(ns+"Name").Value == taxNodeName
                        select node).FirstOrDefault();
    
    Response.Write(Preference.ToString());
    

    节点不为空,但未找到元素,因此在 null 上调用了 .Value

    【讨论】:

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