Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XDocument.Element returns null when parsing an xml string

Tags:

c#

xml

linq

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

like image 772
user3293835 Avatar asked Feb 12 '14 11:02

user3293835


3 Answers

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.

like image 59
Sergey Berezovskiy Avatar answered Nov 18 '22 01:11

Sergey Berezovskiy


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.

like image 5
Henk Holterman Avatar answered Nov 18 '22 00:11

Henk Holterman


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();
like image 3
EZI Avatar answered Nov 17 '22 23:11

EZI