Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath: select specific node which has namespace

Tags:

xml

xpath

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

like image 565
DrDonut Avatar asked Dec 13 '25 02:12

DrDonut


1 Answers

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.

like image 196
Matthew Avatar answered Dec 15 '25 19:12

Matthew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!