LINQ to XML问题由于xml名称空间 [英] LINQ to XML issue due to xml namespace

查看:89
本文介绍了LINQ to XML问题由于xml名称空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Linq从XML中进行选择.这是XML的示例:

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

我遇到的问题是le.Descendants("listing")调用由于名称空间信息而不会从XML文件返回任何结果(我猜是与此相关的问题:

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>

有效.不幸的是,我无权修改xml文件,因此需要一个可行的解决方案.任何帮助表示赞赏.

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

谢谢你, 乔

推荐答案

包含

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

然后尝试

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

这篇关于LINQ to XML问题由于xml名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆