How can I deal with XML a namespace, and XPath without a namespace?

ikantspelwurdz

Well-known member
Joined
Dec 8, 2009
Messages
49
Programming Experience
1-3
Take this sample code:
VB.NET:
        Dim sXml As String = "<n1 xmlns=" & ControlChars.Quote & "n2" & ControlChars.Quote & "><n3>n4</n3></n1>"
        Dim address As String = "n1/n3"

        Dim xDoc As New XmlDocument
        xDoc.LoadXml(sXml)
        Dim xNsmgr As New XmlNamespaceManager(xDoc.NameTable)
        xNsmgr.AddNamespace("n2", "n2")
        Dim s As String = xDoc.SelectSingleNode(address, xNsmgr).InnerText
The first two lines can not be changed. They reflect input coming from an outside system.

As is, this code will not work. The XML namespace is throwing this off.

What's the right way of handling this situation?
 

JohnH

VB.NET Forum Moderator
Staff member
Joined
Dec 17, 2005
Messages
15,431
Location
Norway
Programming Experience
10+
Remove namespaces from input string before parsing it as xml. I particularly liked JSCs simple code to do this here: How to remove all namespaces from XML with C#? - Stack Overflow
Here's a translation of that:
            Dim doc = XDocument.Parse(sXml)

            For Each XE In doc.Root.DescendantsAndSelf
                XE.Name = XE.Name.LocalName
                XE.ReplaceAttributes(From xattrib In XE.Attributes Where Not xattrib.IsNamespaceDeclaration Select New XAttribute(xattrib.Name.LocalName, xattrib.Value))
            Next

            Dim s = doc.XPathSelectElement(address).Value

XPathSelectElement is an extension method you need to import the namespace for:
Imports System.Xml.XPath
 
Top Bottom