7

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

1
  • 1
    Is 'a' your namespace? Commented Feb 12, 2014 at 11:53

4 Answers 4

9

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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.

1 Comment

Default namespace is "schemas.zune.net/catalog/apps/2008/02", which is not the namespace of a.
3
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();

Comments

2

a is a namespace. To get the feed element try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.