簡體   English   中英

XDocument.Element在解析xml字符串時返回null

[英]XDocument.Element returns null when parsing an xml string

我有這個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>

並想獲得<price>值,但是在我的代碼中:

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"); 返回null。 我嘗試刪除該行offers也為空。 我的代碼有什么問題,以及如何獲得price價值? 謝謝

這是獲取價格的正確方法:

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也是名稱空間。

以某種方式獲取名稱空間,例如

XNameSpace a = doc.Root.GetDefaultNamespace();

或者,可能更好:

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

然后在查詢中使用它:

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

您還可以通過文字字符串設置名稱空間,但應避免使用var

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

a是名稱空間。 要獲取feed元素,請嘗試以下操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM