Vishwamohan

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="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Result xmlns="http://TestInfo.com/GetData">
<Data>
<Id>3260</Id>
<StatusCode>0</StatusCode>
<StatusValue>NA</StatusValue>
<Values>
    <Value Type="A">1</Value>
    <Value Type="B">1</Value>
</Values>
</Data>
</Result>
</ResponseData>

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
    xmlDoc.LoadXml(xmlString)
    Dim ns1 As New Xml.XmlNamespaceManager(xmlDoc.NameTable)
    ns1.AddNamespace("t", "http://TestInfo.com/GetData")
 
    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
        Next
    End If
End If
Loading