C# 元素在解析xml字符串时返回null

C# 元素在解析xml字符串时返回null,c#,xml,linq,C#,Xml,Linq,我有以下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"

我有以下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>

Elementa博士;返回null。我试着删除该行也为空。我的代码中有什么错误,如何获得价格值?谢谢

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

XNameSpace a=doc.Root.GetDefaultNamespace;

或者,也许更好:

XNameSpace a = doc.Root.GetNamespaceOfPrefix("a");
然后在查询中使用它:

// to get <a:feed>
XElement f = doc.Element(a + "feed");
您也可以从文本字符串设置名称空间,但要避免变量。

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

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

以下是获取价格的正确方法:

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也是名称空间。

a是您的名称空间吗?默认名称空间是,它不是a的名称空间。
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();
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();