【问题标题】:Querying a LINQ to XML feed in VB.NET在 VB.NET 中查询 LINQ to XML 提要
【发布时间】:2011-03-09 20:31:48
【问题描述】:

我有以下通过XDocument.Load(uri)XElement.Load(uri) 加载的XML。我无法通过 LINQ 获取 <asset> 元素的集合。

这是我要查询的 XML 的 sn-p:

<assetCollection xmlns="tag:aisle7.net,2009:/api/1.0">
      <title>All Assets</title>
      <description>Collection containing all assets in the system</description>
      <resourcePath>/us/assets/~all</resourcePath>
      <link rel="self" href="http://web.aisle7.net/api/1.0/us/assets/~all?apikey=1234567890&amp;Format=XML" />
      <link rel="first" href="http://web.aisle7.net/api/1.0/us/assets/~all?apikey=1234567890&amp;Format=XML" />
      <link rel="next" href="http://web.aisle7.net/api/1.0/us/assets/~all?apikey=1234567890&amp;Format=XML&amp;page=2" />
      <link rel="last" href="http://web.aisle7.net/api/1.0/us/assets/~all?apikey=1234567890&amp;Format=XML&amp;page=66" />
      <updated>2011-03-01T19:01:49.667Z</updated>
      <assets>
        <asset>
          <title>Homeopathy</title>
          <resourcePath>/us/assets/toc/homeopathy</resourcePath>
          <link rel="alternate" href="http://web.aisle7.net/api/1.0/us/assets/toc/homeopathy?apikey=1234567890&amp;Format=XML" />
          <updated>2011-03-01T19:01:49.667Z</updated>
        </asset>
        <asset>
          <title>What Is Homeopathy?</title>
          <resourcePath>/us/assets/generic/what-is-homeopathy_13615_1</resourcePath>
          <link rel="alternate" href="http://web.aisle7.net/api/1.0/us/assets/generic/what-is-homeopathy_13615_1?apikey=1234567890&amp;Format=XML" />
          <updated>2011-03-01T19:00:17.680Z</updated>
        </asset>
    ...

这是我尝试使用的代码:

Dim uri As String = HttpUtility.UrlDecode(ConfigurationManager.AppSettings("Aisle7_Index_Url"))

Dim assets = (From a In XElement.Load(uri)
                               .Element("assets")
                               .Elements("asset")
             Select a)

For Each asset In assets
  Console.WriteLine(asset)
Next

【问题讨论】:

    标签: vb.net linq linq-to-xml


    【解决方案1】:

    试试

    Dim assets = From a In XElement.Load(uri).Descendants("asset") Select a
    

    Dim assets = From a In XDocument.Load(uri).Root.Element("assets").Elements("asset") Select a
    

    【讨论】:

    • 没有骰子。调试 'assets' 显示消息“抛出了 'System.Linq.SystemCore_EnumerableDebugViewEmptyException' 类型的异常。”在检查员中。有什么想法吗?
    • 您刚刚发布的第二个 sn-p 引发 NullReferenceException :(
    • @Mark 显然它不喜欢你的 `xmlns="tag:aisle7.net,2009:/api/1.0"' 。如果我删除它,两个 sn-ps 都可以正常工作。
    • 我刚刚发现自己......有什么办法让 LINQ 忽略命名空间?
    • @马克酷。也看看这篇文章bohu7.wordpress.com/2008/12/11/…
    【解决方案2】:

    这是使用 xml 文字语法的版本:

    Dim xml = XElement.Load(uri)
    Dim q = From a In xml.<assets>...<asset> 
            Select a
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-07
      • 1970-01-01
      • 2010-12-02
      • 2010-10-22
      相关资源
      最近更新 更多