Selecting a node with multiple namespace values โ€‹โ€‹in an XML document returns nothing

The presence of an xml file, for example:

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

 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 getting "Nothing" while reading xml. Is there a way to ignore namespaces ?. The problem is that some namespaces may differ between files, so I added the GetNameSpaceManager function ...

0
source share
1 answer

In XPath, the name of an element without a prefix is โ€‹โ€‹always considered in an empty namespace. In XML, however, there is a default namespace that elements inherit differently by default, this is in your specific XML:

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

I would suggest using a default prefix, such as d , in your XPath. And then map the prefix to the root element 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 in both cases (an XML document with and without a default namespace), but not in the case of XML with a default namespace declared locally at the descendant level.

+1
source

Source: https://habr.com/ru/post/1238047/


All Articles