0

Having an xml file like:

<?xml version="1.0" encoding="UTF-8"?>
<Data Version="3" xsi:schemaLocation="uuid:ebfd9-45-48-a9eb-42d Data.xsd" xmlns="uuid:ebfd9-45-48-a9eb-42d" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Info>
    <Muc>Demo</Muc>
  </Info>
</Data>

I am doing

Dim m_xmld As XmlDocument
m_xmld = New XmlDocument()
m_xmld.Load("myXML.xml")
Dim test As XmlNode
test = doc.SelectSingleNode("Data/Info", GetNameSpaceManager(m_xmld))

having:

 Public Shared Function GetNameSpaceManager(ByRef xDoc As XmlDocument) As XmlNamespaceManager
        Dim nsm As New XmlNamespaceManager(xDoc.NameTable)
        Dim RootNode As XPathNavigator = xDoc.CreateNavigator()
        RootNode.MoveToFollowing(XPathNodeType.Element)
        Dim NameSpaces As IDictionary(Of String, String) = RootNode.GetNamespacesInScope(XmlNamespaceScope.All)
        For Each kvp As KeyValuePair(Of String, String) In NameSpaces
            nsm.AddNamespace(kvp.Key, kvp.Value)
        Next
        Return nsm
    End Function

However I keep on getting "Nothing" when reading the xml. Is there a way to ignore the namespaces?. The issue is that some namespaces may vary between files, thats why I added GetNameSpaceManager function...

edgarmtze
  • 24,683
  • 80
  • 235
  • 386

1 Answers1

1

In XPath, element name without prefix is always considered in empty namespace. In XML though, there is default namespace which elements implicitly inherits by default, this one in your particular XML :

xmlns="uuid:ebfd9-45-48-a9eb-42d"

I'd suggest to use a default prefix, say d, in your XPath. And then map the prefix to the root element's namespace :

......
Dim nsManager As New XmlNamespaceManager(New NameTable())
nsManager.AddNamespace("d", m_xmld.DocumentElement.NamespaceURI)
test = doc.SelectSingleNode("d:Data/d:Info", nsManager)

The above will work on both cases (XML document with and without default namespace), but not in case an XML with default namespace declared locally at the descendant elements level.

har07
  • 88,338
  • 12
  • 84
  • 137
  • I think is a good option, however Is there a way to include this inside the `GetNameSpaceManager` ? because in that function I add the namespace like `nsm.AddNamespace(kvp.Key, kvp.Value)` ? – edgarmtze Dec 14 '15 at 02:02
  • Simply add another line just before `Return nsm` to add the default namespace prefix. I'd also suggest to use prefix that unlikely to be used in the actual XML to avoid conflict, something like : `nsm.AddNamespace("__d", xDoc.DocumentElement.NamespaceURI)` – har07 Dec 14 '15 at 02:08