Nathan
Nathan

Reputation: 1425

I'm having trouble querying an XDocument using LINQ

I'm new to LINQ so I gather I just have some of my syntax wrong. I've looked at many examples online but everyone seems to have their own style.

Here's the XML data I'm querying against:

<ajax-response>
    <response type="object" id="unknown">
        <generic response="Success" message="Channel status will follow" />
    </response>
    <response type="object" id="unknown">
        <generic event="Status" privilege="Call" channel="SIP/452-000006fc" calleridnum="452" calleridname="Joe" connectedlinenum="430" connectedlinename="device" accountcode="" channelstate="6" channelstatedesc="Up" context="macro-dial-one" extension="s" priority="37" seconds="54" bridgedchannel="SIP/430-000006fd" bridgeduniqueid="1363822334.1829" uniqueid="1363822334.1828" />
    </response>
    <response type="object" id="unknown">
        <generic event="Status" privilege="Call" channel="SIP/430-000006fd" calleridnum="430" calleridname="device" connectedlinenum="452" connectedlinename="Joe" account="" state="Up" bridgedchannel="SIP/452-000006fc" bridgeduniqueid="1363822334.1828" uniqueid="1363822334.1829" />
    </response>
    <response type="object" id="unknown">
        <generic event="StatusComplete" items="2" />
    </response>
</ajax-response>

and here's what I have so far:

Function ParseXML(statusXML As XmlDocument) As String
    Dim xdoc As XDocument = XDocument.Load(New XmlNodeReader(statusXML))
    Dim parsed As StringBuilder = New StringBuilder()

    Dim query = From generic In xdoc.Descendants("generic") _
                Where generic.Attribute("privilege") IsNot Nothing And generic.Attribute("privilege").Value = "Call" _
                Select connectedlinenum = generic.Attribute("connectedlinenum").ToString, _
                       calleridnum = generic.Attribute("calleridnum").ToString

    For Each i In query
        parsed.Append(i.connectedlinenum).Append(",").Append(i.calleridnum).Append(vbCrLf)
    Next
    Return parsed.ToString
End Function

I'm guessing I am misunderstanding how my generic object is supposed to be working, because I get a NullReferenceException in my Where clause when I try to reference it.

Upvotes: 0

Views: 126

Answers (1)

yu_ominae
yu_ominae

Reputation: 2935

I'm not familiar with Xml parsing, but in two of the nodes you do not have the privilege attribute. Could that be causing the error?

In that case, what happens if you change the And to AndAlso in the Where clause? That way it would not evaluate the latter part of the statement if there is no privilege attribute.

Upvotes: 1

Related Questions