我在使用LINQ查询XDocument时遇到了麻烦

时间:2013-03-21 01:15:15

标签: asp.net vb.net linq linq-to-xml

我是LINQ的新手所以我收集我的一些语法错误。我在网上看了很多例子,但每个人似乎都有自己的风格。

这是我要查询的XML数据:

<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>

这是我到目前为止所拥有的:

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

我猜我误解了我的generic对象应该如何工作,因为当我尝试引用它时,我在Where子句中得到NullReferenceException

1 个答案:

答案 0 :(得分:1)

我不熟悉Xml解析,但是在两个节点中你没有privilege属性。这会导致错误吗?

在这种情况下,如果您将And条款中的AndAlso更改为Where会怎样?这样,如果没有privilege属性,它就不会评估语句的后半部分。