简体   繁体   English

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

[英]Query XML using linq and comparing two variable

Trying to write a select that will let me select a specific office element 试图写一个选择,让我选择一个特定的办公室元素

Here is my XML 这是我的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>

Here is my code 这是我的代码

    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

I think my issue is somewhere around here: And office.Element("name").Value = selectOffice 我认为我的问题就在这里:和office.Element(“ name”)。Value = selectOffice

Thanks for your help everyone, the issue was I had an office element at the wrong level in the second region. 谢谢大家的帮助,问题是我在第二个区域的办公室级别错误。

It looks like your issue is that clfWizardXml.Elements("region") doesn't return anything, since region is not directly under the document. 看来您的问题是clfWizardXml.Elements("region")不返回任何内容,因为region不在文档的正下方。 Instead you need clfWizardXml.Root.Elements("region") , or clfWizardXml.Descendants("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

Also, since VB.NET supports XML literals, you can make it look a little nicer (to me anyway, you may disagree): 另外,由于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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM