LINQ to XML issue due to xml namespace

你离开我真会死。 提交于 2019-12-12 09:48:31

问题


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:


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


来源:https://stackoverflow.com/questions/7591237/linq-to-xml-issue-due-to-xml-namespace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!