user1590636
user1590636

Reputation: 1194

Linq to XML is not getting any elements

trying to parse this xml file

<?xml version="1.0" encoding="UTF-8"?>
<feed gd:kind="shopping#products"
      gd:etag="&quot;pUAQLMOCjdnNh1LcpqK05ByVY7g/Gsdf7eFzzI3Z-HW0Z-XItKMrp8c&quot;"
      xmlns="http://www.w3.org/2005/Atom"
      xmlns:gd="http://schemas.google.com/g/2005"
      xmlns:s="http://www.google.com/shopping/api/schemas/2010">
    <entry gd:kind="shopping#product">
        <s:product>
            <s:googleId>11111</s:googleId>
            <s:author>
                <s:name>ebay.de</s:name>
                <s:accountId>11111</s:accountId>
            </s:author>
            <s:creationTime>2012-08-16T19:20:24.000Z</s:creationTime>
            <s:modificationTime>2013-03-01T17:50:54.000Z</s:modificationTime>
            <s:country>It</s:country>
            <s:language>de</s:language>
            <s:title>Blomus Rund-Magnete</s:title>
            <s:brand>Blomus</s:brand>
            <s:condition>new</s:condition>
            <s:mpns>
                <s:mpn>66742</s:mpn>
            </s:mpns>
            <s:inventories>
                <s:inventory channel="online" availability="inStock">
                    <s:price shipping="4.9" currency="EUR">4.2</s:price>
                </s:inventory>
            </s:inventories>
            <s:images>
            </s:images>
        </s:product>
    </entry>
</feed>

LINQ:

XNamespace s = "http://www.google.com/shopping/api/schemas/2010";

var q = from product in XMLDoc.Root.Elements("entry").Elements(s+"product")
        let inventory = product.Element(s + "inventories").Element(s + "inventory")
        let price = (decimal)inventory.Element(s + "price")
        let shipping = (decimal)inventory.Element(s +"price").Attribute("shipping")
        let totalprice = price + shipping
        select new
        {
            Name = (string)product.Element(s + "author").Element(s + "name"),
            Shipping = shipping,
            TotalPrice = totalprice,
            Price = price+shipping
        };

the returned q count is always 0, what might be wrong?!

Upvotes: 2

Views: 145

Answers (1)

aush
aush

Reputation: 2108

Your entry is missing the namespace. I've tried to replace it to s:entry (and XMLDoc.Root.Elements("entry") to XMLDoc.Root.Elements(s + "entry")) and your query's worked fine.

The problem is that you have defined the default namespace xmlns="http://www.w3.org/2005/Atom". So, you have to use it too for elements with no prefix like this:

XNamespace def = "http://www.w3.org/2005/Atom";

And then xDoc.Root.Elements(def + "entry").

Upvotes: 2

Related Questions