Welcome to Vishwa's blog - Technology, Spirituality and More...

Reading XML with Namespace

If your XML contains Namespace information, then following example illustrates as how to read the data

Let’s consider following XML saved as TestResp.xml

This example contains elements and attribute.

<ResponseData xmlns:xsi="" xmlns:xsd="">
<Result xmlns="">
    <Value Type="A">1</Value>
    <Value Type="B">1</Value>

Now, let’s read the info

Dim xmlString As String = ""
If File.Exists("C:\Test\TestResp.xml") Then xmlString = File.ReadAllText("C:\Test\TestResp.xml")
If String.IsNullOrEmpty(xmlString) = False Then
    xmlDoc = New Xml.XmlDocument
    Dim ns1 As New Xml.XmlNamespaceManager(xmlDoc.NameTable)
    ns1.AddNamespace("t", "")
    If xmlDoc.SelectSingleNode("//t:Result/t:Data/t:Id", ns1) IsNot Nothing AndAlso _
                   IsNumeric(xmlDoc.SelectSingleNode("//t:Result/t:Data/t:Id", ns1).InnerText) Then
        Dim id As String = xmlDoc.SelectSingleNode("//t:Result/t:Data/t:Id", ns1).InnerText
    End If
    If xmlDoc.SelectSingleNode("//t:Result/t:Data/t:Values/t:Value", ns1) IsNot Nothing Then
        Dim xmlnodes As Xml.XmlNodeList = xmlDoc.SelectNodes("//t:Result/t:Data/t:Values/t:Value", ns1)
        For Each nod As Xml.XmlNode In xmlnodes
            If nod.Attributes("Type").Value = "A" Then
                Dim valueTypeA As String = nod.InnerText
            End If
    End If
End If