Vishwamohan

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

Parsing XML with multiple namespaces

You may come across a situation when you will have to read a XML document containing name spaces and assign values to it. Here is sample which includes multiple namespaces with SOAP envelope xml document.

Test.XML

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <GetRecord xmlns="http://services.sample.com">
      <Request xmlns:a="http://schemas.sample.com/2013/06/GetRecordRequest" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <LoginData>
          <UserID>UserName</UserID>
          <Password>password</Password>
          <RequestID>23232323</RequestID>
          <IPAddress>121.11.1.1</IPAddress>
        </LoginData>
        <a:RecordID>35488047</a:RecordID>
      </Request>
    </GetRecord>
  </s:Body>
</s:Envelope>

 

Function which reads and assign values 

Private Function ReadAndAssignRequestXML(ByVal recordID As String) As String
Dim xmlDoc As New XmlDocument
Dim InputSOAPXML As String = String.Empty
Dim xmlFileName As String = "C:\Test.xml"


Try
xmlDoc.Load(xmlFileName)
Dim nsmgr As XmlNamespaceManager = New XmlNamespaceManager(xmlDoc.NameTable)
nsmgr.AddNamespace("a", "http://schemas.sample.com/2013/06/GetRecordRequest")
nsmgr.AddNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/")
nsmgr.AddNamespace("l", "http://services.sample.com")

xmlDoc.SelectSingleNode("/s:Envelope/s:Body/l:GetRecord/l:Request/l:LoginData/l:UserID", nsmgr).InnerText = "myUserID"
xmlDoc.SelectSingleNode("/s:Envelope/s:Body/l:GetRecord/l:Request/l:LoginData/l:Password", nsmgr).InnerText = "PASS"
xmlDoc.SelectSingleNode("/s:Envelope/s:Body/l:GetRecord/l:Request/a:RecordID", nsmgr).InnerText = recordID

InputSOAPXML = xmlDoc.OuterXml

Catch ex As Exception
InputSOAPXML = ex.Message
End Try

Return InputSOAPXML
End Function

 
Loading