我怎样才能正确编写WHERE子句?

时间:2015-01-19 15:03:28

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

我有一个XML文件,其结构如下:

<root>
   <State state="AZ" stateName="Arizona" stateKey="Arizona" >
      <menuVirtualPageName>Arizona.html</menuVirtualPageName>
      <Region regionKey="GreaterPhoenix" >
         <pageName>Phoenix.html</pageName>
      </Region>
   </State>
</root>

我一直在尝试使用regionKey值来选择状态。鉴于我已经为“thisState”提供了正确的值,我编写了以下Linq查询

Dim stateQuery = (From dataStates In dataStatesXML...<Region> Where dataStatesXML...<State>.@stateKey = thisState Select New With {.virtualPageName = dataStates.<menuVirtualPageName>.Value.ToString(), .stateName = dataStates.@stateName.ToString()})

但我总是得到一个空的查询结果:(任何想法或建议非常赞赏!!!

1 个答案:

答案 0 :(得分:1)

试试这个: -

Dim state As String = (From x In xdoc.Descendants("Region") _
                    Where x.Attribute("regionKey").Value = "GreaterPhoenix" _
                    Select x.Parent.Attribute("state").Value).FirstOrDefault()

我收到AZ作为输出。

修改

刚刚注意到您想要抓取stateName&amp; virtualPageName同样,以下是对此的查询: -

Dim result = (From x In xdoc.Descendants("Region") _
   Where x.Attribute("regionKey").Value = "GreaterPhoenix"
   Select New With {.virtualPageName = x.Parent.Element("menuVirtualPageName").Value, _
                    .stateName = x.Parent.Attribute("stateName").Value}).ToList()