简体   繁体   English

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

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

I have this 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>

and want to get value of <price> but here in my codes: 并想获得<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"); returns null. 返回null。 I tried removing that line offers is also null. 我尝试删除该行offers也为空。 what is wrong in my code and how to get value of price ? 我的代码有什么问题,以及如何获得price价值? thanks 谢谢

Here is correct way to get prices: 这是获取价格的正确方法:

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

Keep in mind that your document have default namespace, and a is also namespace. 请记住,您的文档具有默认名称空间,并且a也是名称空间。

Get the namespace somehow, like 以某种方式获取名称空间,例如

XNameSpace a = doc.Root.GetDefaultNamespace();

or, probably better: 或者,可能更好:

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

and then use it in your queries: 然后在查询中使用它:

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

You can also set the namespace from a literal string, but then avoid var . 您还可以通过文字字符串设置名称空间,但应避免使用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 is a namespace. a是名称空间。 To get the feed element try this: 要获取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