【问题标题】:XDocument.Element returns null when parsing an xml stringXDocument.Element 在解析 xml 字符串时返回 null
【发布时间】:2014-02-12 11:46:55
【问题描述】:

我有这个 xml 字符串:

<a:feed xmlns:a="http://www.w3.org/2005/Atom" 
        xmlns:os="http://a9.com/-/spec/opensearch/1.1/"
        xmlns="http://schemas.zune.net/catalog/apps/2008/02">
    <a:link rel="self" type="application/atom+xml" href="/docs" />
    <a:updated>2014-02-12</a:updated>
    <a:title type="text">Chickens</a:title>
    <a:content type="html">eat 'em all</a:content>
    <sortTitle>Chickens</sortTitle>
    ... other stuffs
    <offers>
        <offer>
            <offerId>8977a259e5a3</offerId>
            ... other stuffs
            <price>0</price>
            ... other stuffs
        </offer>
    </offers>
    ... other stuffs
</a:feed>

并希望获得 &lt;price&gt; 的值,但在我的代码中:

XDocument doc = XDocument.Parse(xmlString);
var a = doc.Element("a");
var offers = a.Element("offers");
foreach (var offer in offers.Descendants())
{
   var price = offer.Element("price");
   var value = price.Value;
}

doc.Element("a"); 返回空值。我尝试删除该行 offers 也是空的。我的代码有什么问题以及如何获得price 的值?谢谢

【问题讨论】:

  • “a”是你的命名空间吗?

标签: c# xml linq


【解决方案1】:

这是获取价格的正确方法:

var xdoc = XDocument.Parse(xmlString);
XNamespace ns = xdoc.Root.GetDefaultNamespace();

var pricres = from o in xdoc.Root.Elements(ns + "offers").Elements(ns + "offer")
              select (int)o.Element(ns + "price");

请记住,您的文档具有默认命名空间,a 也是命名空间。

【讨论】:

    【解决方案2】:

    以某种方式获取命名空间,例如

    XNameSpace a = doc.Root.GetDefaultNamespace();

    或者,可能更好:

    XNameSpace a = doc.Root.GetNamespaceOfPrefix("a");
    

    然后在您的查询中使用它:

    // to get <a:feed>
    XElement f = doc.Element(a + "feed");
    

    您也可以从文字字符串设置命名空间,但要避免使用var

    【讨论】:

    【解决方案3】:
    var xDoc = XDocument.Load(filename);
    XNamespace ns = "http://schemas.zune.net/catalog/apps/2008/02";
    var prices = xDoc
                    .Descendants(ns + "offer")
                    .Select(o => (decimal)o.Element(ns + "price"))
                    .ToList();
    

    【讨论】:

      【解决方案4】:

      a 是一个命名空间。要获取提要元素,请尝试以下操作:

      XDocument doc = XDocument.Parse(xmlString);
      XNamespace a = "http://www.w3.org/2005/Atom";
      var feed = doc.Element(a + "feed");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-15
        • 2021-04-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多