XDocument.Element解析XML字符串时返回null [英] XDocument.Element returns null when parsing an xml string
本文介绍了XDocument.Element解析XML字符串时返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的XML字符串:
I have this xml string:
<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:
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。我试图消除这一行报价
也为空。什么是错在我的代码,以及如何让价格
的价值?谢谢
doc.Element("a");
returns null. I tried removing that line offers
is also null. what is wrong in my code and how to get value of price
? thanks
推荐答案
获取命名空间不知何故,像
Get the namespace somehow, like
<击>
的XNamespace A = doc.Root.GetDefaultNamespace();
击>
或者,可能会更好:
XNameSpace a = doc.Root.GetNamespaceOfPrefix("a");
,然后用它在查询:
and then use it in your queries:
// to get <a:feed>
XElement f = doc.Element(a + "feed");
您还可以设置从一个字符串的命名空间,但避免 VAR
。
You can also set the namespace from a literal string, but then avoid var
.
这篇关于XDocument.Element解析XML字符串时返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文