0
Dim lstrReadXml As String = String.Empty
mobjComFun.ReadTextFile(System.Windows.Forms.Application.StartupPath & "\GoFirstBookingXML\GetBookRes.xml", lstrReadXml)
Dim lobjXdoc As XDocument = XDocument.Parse(lstrReadXml)
Dim lobjNs As New XmlNamespaceManager(lobjXdoc.CreateReader.NameTable)
lobjNs.AddNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/")
lobjNs.AddNamespace("sc", "http://schemas.navitaire.com/WebServices/ServiceContracts/BookingService")
lobjNs.AddNamespace("dc", "http://schemas.navitaire.com/WebServices/DataContracts/Booking")
lobjNs.AddNamespace("a", "http://schemas.navitaire.com/WebServices/DataContracts/Common")
 
Dim lstrErrorMsg = String.Empty, lstrQueryStr As String = String.Empty
Dim lstrPaxNames As New StringBuilder
'Dim lstrFirstName As String = mobjComFun.GetElementValue(lobjXdoc, "/s:Envelope/s:Body/sc:GetBookingResponse/dc:Booking/dc:Passengers/dc:Passenger/dc:Names", lobjNs, lstrErrorMsg)
For Each lobXnode In lobjXdoc.XPathSelectElements("/s:Envelope/s:Body/sc:GetBookingResponse/dc:Booking/dc:Passengers/dc:Passenger", lobjNs)
    If Not lobXnode Is Nothing Then
        Dim lobjIEnum As IEnumerable(Of XElement) = From Nam In lobXnode.Elements(lobjNs. & "Names")
                                                    Select Nam

        Dim lstrLN As String = lobXnode.Document.Element("LastName").Value
        lstrPaxNames.Append(lobXnode.XPathSelectElement("/dc:Names", lobjNs).Value)
        lstrPaxNames.Append(lobXnode.XPathSelectElement("/dc:Names/dc:BookingName/dc:LastName", lobjNs).Value & "/")
        lstrPaxNames.Append(lobXnode.XPathSelectElement("/dc:Names/dc:BookingName/dc:FirstName", lobjNs).Value & " Y58TWL ")

    End If
Next

When trying to foreach iterate the XDocument, I receive the object reference error when trying to get the element value inside the iteration.

Mario Z
  • 4,328
  • 2
  • 24
  • 38
Naresh
  • 1
  • 2
  • 2
    1) Is that really [tag:vba] or is it actually [tag:vb.net]? 2) Please [edit] your question to include an XML sample that reproduces the problem -- i.e., a [mcve]. See [ask]. – dbc Dec 28 '22 at 16:48
  • `Dim lstrLN As String = lobXnode.Document.Element("LastName").Value` will throw a null reference exception. `lobXnode.Document` returns the **`XDocument` containing `lobXnode`**, i.e. `lobjXdoc`. Thus `lobXnode.Document.Element("LastName")` will return the root node of the document if and only if it is named ``. But we know the root node is named `` so `.Element("LastName")`` will return null, and `.Value` will fail with a null reference exception. You never use `lstrLN` though, so remove that line. (We still need to see an XML sample to answer your question though.) – dbc Dec 29 '22 at 15:02

0 Answers0