0

如何使用 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());
4

1 回答 1

0

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

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());

该节点不为空,但未找到该元素,因此.Value被调用null

于 2013-01-16T14:22:55.337 回答