【问题标题】:XPath: select specific node which has namespaceXPath:选择具有命名空间的特定节点
【发布时间】:2016-03-18 10:34:47
【问题描述】:

我需要在 xml 文档中选择一个节点,但它上面级别的节点有一个命名空间。如何做到这一点?

我的 xml 文件的一部分:

<SW.DataBlock ID="0">
<AttributeList>
  <DatablockType>SharedDB</DatablockType>
  <Interface>
    <Sections xmlns="http://www.siemens.com/automation/Openness/SW/Interface/v1">
        <Section Name="Static">
            <Member Name="DbBool1" Datatype="Bool" />
            <Member Name="DbA" Datatype="&quot;DataTypeA&quot;" />
            <Member Name="AddedDbB" Datatype="&quot;DataTypeB&quot;" />
        </Section>
    </Sections>
  </Interface>
  <MemoryLayout>Standard</MemoryLayout>
  <Name>DataA</Name>
  <Number>1</Number>
  <ProgrammingLanguage>DB</ProgrammingLanguage>
  <Type>DB</Type>
</AttributeList>
</SW.DataBlock>

这是我需要获取的“部分”节点。由于命名空间,声明:

node2 = node.SelectSingleNode("//Section")

不起作用。我需要用什么来代替“//Section”部分才能使其工作?

编辑:我使用带有 System.Xml 包的 vb.Net

【问题讨论】:

    标签: xml xpath


    【解决方案1】:

    这取决于您用来处理 xpath 的软件。使用纯 xpath 能做的最好的事情是

    //*[local-name()='Section']
    

    这会选择名称为 Section 的所有元素,而不管它们的命名空间如何。

    如果你需要指定命名空间中的这个元素,你可以这样做

    //*[local-name()='Section' and namespace-uri()='http://www.siemens.com/automation/Openness/SW/Interface/v1']
    

    很多处理xpath的工具也有注册命名空间的方法,然后就可以使用像这样的限定形式

    //ns:Section
    

    我不熟悉 VB 或这个包,但看起来您可以使用 XmlNamespaceManager 类来注册命名空间,然后将其作为第二个参数传递给您正在使用的方法。这将允许您使用如图所示的前缀版本。

    the documentation 的示例显示了如何使用此类的以下示例。

    Dim reader As New XmlTextReader("myfile.xml")
    Dim nsmanager As New XmlNamespaceManager(reader.NameTable)
    nsmanager.AddNamespace("msbooks", "www.microsoft.com/books")
    nsmanager.PushScope()
    nsmanager.AddNamespace("msstore", "www.microsoft.com/store")
    While reader.Read()
        Console.WriteLine("Reader Prefix:{0}", reader.Prefix)
        Console.WriteLine("XmlNamespaceManager Prefix:{0}",
         nsmanager.LookupPrefix(nsmanager.NameTable.Get(reader.NamespaceURI)))
    End While
    

    从示例中删除的关键项目是命名空间管理器的创建和命名空间的添加。然后你只需将它传递给 SelectSingleNode 方法。

    【讨论】:

      猜你喜欢
      • 2010-10-06
      • 1970-01-01
      • 1970-01-01
      • 2018-05-30
      • 2012-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-16
      相关资源
      最近更新 更多