【问题标题】:Why does it select only one single element with LINQ to XML?为什么使用 LINQ to XML 只选择一个元素?
【发布时间】:2013-12-17 17:22:14
【问题描述】:

我正在使用 LINQ to XML 恢复 machine.config 文件的绑定指令。我有很多,比如:

<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="Mityc.Sigetel.ComplaintsTeams" publicKeyToken="159574ffe4118e68"/>
    <bindingRedirect oldVersion="1.0.0.0-1.0.5.65535" newVersion="1.0.5.18135"/>
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Mityc.Sigetel.Ham" publicKeyToken="159574ffe4118e68"/>
    <bindingRedirect oldVersion="1.0.0.0-5.2.0.65535" newVersion="5.2.0.21977"/>
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Mityc.Sigetel.Common.Territories" publicKeyToken="159574ffe4118e68"/>
    <bindingRedirect oldVersion="1.0.0.0-1.1.2.65535" newVersion="1.1.2.20631"/>
  </dependentAssembly>

但是,如果我写这个,我只能恢复一个元素(有很多):

''' <summary>
''' Load the framework machine.config file.
''' </summary>
Public Sub Load()
    Dim machineFile As XDocument = XDocument.Load(_pathToFile)
    Dim iWantMoreElements = machineFile.Descendants("dependentAssembly").ToList()
    'iWantMoreElements.Count = 1
End Sub

我怎样才能恢复所有这些?非常感谢。

【问题讨论】:

  • 你的From dependentAssembly In 没用。
  • 是的,你是对的。我在我的代码中更改了它。谢谢。
  • 应该可以。我在 C# 中试了一下,得到了三个条目。
  • 非常感谢您的帮助,但我终于找到了原因:assemblyBinding 元素的命名空间。我必须在代码中指定它。

标签: .net xml vb.net linq


【解决方案1】:

好的,问题在于命名空间。 XML 中的父元素 assemblyBinding 具有指定的命名空间。所以,如果我想从 root 元素中恢复它的子元素,我必须这样写:

Public Sub Load()
    Dim machineFile As XDocument = XDocument.Load(_pathToFile)
    Dim ns As XNamespace = "urn:schemas-microsoft-com:asm.v1"
    Dim iWantMoreElements = machineFile.Descendants(ns + "dependentAssembly").ToList()
    'iWantMoreElements.Count = 32
End Sub

我只恢复了一个元素,因为该元素指定了一个类似 xmlns="" 的命名空间。其余的,不是。

非常感谢您的帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-04
    • 1970-01-01
    • 2023-03-06
    相关资源
    最近更新 更多