简体   繁体   中英

XPath: select specific node which has namespace

I need to select a node in an xml document, but the node in the level above it has a namespace. How to do this?

Part of my xml file:

<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>

It is the 'section' node which I need to get. Because of the namespace, the statement:

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

does not work. What do I need to put in place of the "//Section" part to make it work?

Edit: I use vb.Net with the System.Xml Package

This depends on the software you are using to process the xpath. The best you can do with pure xpath is

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

This selects all elements whose name is Section regardless of their namespace.

If you need this element in a specified namespace, you can do

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

Many tools for processing xpath also have methods of registering a namespace, and then you can use a qualified form like

//ns:Section

I am not familiar with VB or this package, but it looks like you can use the XmlNamespaceManager class to register the namespace and then pass that to the method you are using as a second argument. That will allow you to use a prefixed version like shown.

The example from the documentation shows the following example of how to use this class.

 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 

The key items to take away from the example are the creation of the namespace manager and the adding of a namespace. Then you just pass it to the SelectSingleNode method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM