3

I am trying to use Linq to select from XML. Here is an example of the XML:

<?xml version="1.0" encoding="UTF-8"?>
<listingexport xmlns="http://websitexmlfeed.com/webservice/2/listings"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://websitexmlfeed.com/webservice/2/listings ../listings.xsd">
<listing>
    <id>00001</id>
    <name>Modelname</name>
    <type>Typename</type>
</listing>
</listingexport>

The code I am using is as follows:

XDocument le = XDocument.Load(@uri);
var listings = (from listing in le.Descendants("listing")
                       select new listingType
                       {
                           Id = listing.Element("id").Value,
                           Name= listing.Element("name").Value,
                           Type= listing.Element("type").Value
                        }).ToList();

Problem I have is that the le.Descendants("listing") call doesnt return any results from the XML file due to the namespace information (i guess an issue related to this post: ASP.NET 2.0 XmlDataSource's XPath doesn't support namespaces). However, If I modify the XML file so there is no namespace information as so:

<?xml version="1.0" encoding="UTF-8"?>
  <listingexport>
   <listing>
    <id>00001</id>
    <name>Modelname</name>
    <type>Typename</type>
   </listing>
  </listingexport>

it works. Unfortunately I do not have access to modify the xml file so need a solution that will work. Any help appreciated.

thank you, Joe

1 Answer 1

4

Include

XNamespace ns  = "http://websitexmlfeed.com/webservice/2/listings";

and try

var listings = (from listing in le.Descendants(ns + "listing")
                       select new 
                       {
                           Id = listing.Element(ns + "id").Value,
                           Name= listing.Element(ns + "name").Value,
                           Type= listing.Element(ns + "type").Value
                        }).ToList();
Sign up to request clarification or add additional context in comments.

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.