使用linq查询XML并比较两个变量

时间:2014-06-19 20:33:20

标签: vb.net linq

尝试编写一个允许我选择特定办公室元素的选择

这是我的XML

<?xml version="1.0"> 
<regions>
    <region>
        <office>
            <name>Office One</name>
        </office>

        <office>
            <name>Office Two</name>
        </office>
        <settings>
            <name>Main Regional Name</name>
        </settings>
    </region>
    <region>
        <office>
            <name>Office Three</name>
        </office>

        <office>
            <name>Office Four</name>
        </office>
        <settings>
            <name>Secondary Regional Name</name>
        </settings>
    </region>

这是我的代码

    Dim clfWizardXml As XElement
    Dim selectRegion = lstRegions.SelectedItem
    Dim selectOffice = lstOffices.SelectedItem


    Console.WriteLine(selectRegion + " " + selectOffice)


    Dim officeList As IEnumerable(Of XElement) = _
        From region In clfWizardXml.Elements("region"), _
             office In clfWizardXml.Elements("region").Elements("office") _
        Where region.Element("settings").Element("name").Value = selectRegion _
        And office.Element("name").Value = selectOffice
        Select office

我认为我的问题就在这附近: 和office.Element(&#34; name&#34;)。Value = selectOffice

感谢大家的帮助,问题是我在第二个地区的办公室元素处于错误的位置。

1 个答案:

答案 0 :(得分:0)

看起来您的问题是clfWizardXml.Elements("region")没有返回任何内容,因为region不在文档的正下方。相反,您需要clfWizardXml.Root.Elements("region")clfWizardXml.Descendants("region")

Dim officeList As IEnumerable(Of XElement) = _
    From region In clfWizardXml.Root.Elements("region"), _
         office In clfWizardXml.Root.Elements("region").Elements("office") _
    Where region.Element("settings").Element("name").Value = selectRegion _
    And office.Element("name").Value = selectOffice
    Select office

此外,由于VB.NET支持XML文字,你可以让它看起来更好一些(无论如何,你可能不同意):

Dim officeList As IEnumerable(Of XElement) =
    From region In clfWizardXml...<region>,
         office In region.<office>
    Where region.<settings>.<name>.Value = selectRegion _
        AndAlso office.<name>.Value = selectOffice
    Select office