简体   繁体   中英

Troubles searching xml document with LINQ

I have an xml document that has 3 elements in this format:

<Codes>
    <Code>
        <CodeScenario>3</CodeScenario>
        <CodeScenario>4</CodeScenario>
        <CodeScenario>6</CodeScenario>
        <CodeScenario>7</CodeScenario>
        <CodeCategory>Category3</CodeCategory>
        <CodeID>043</CodeID>
        <CodeDescription>Description3</CodeDescription>
        <CodeType>PE</CodeType>
        </Code>
    <Code>
        <CodeCategory>Category2</CodeCategory>
        <CodeID>046</CodeID>
        <CodeDescription>Description2</CodeDescription>
        <CodeType>PE</CodeType>
    </Code>
    <Code>
        <CodeScenario>2</CodeScenario>
        <CodeCategory>Category1</CodeCategory>
        <CodeID>100</CodeID>
        <CodeDescription>Description1</CodeDescription>
        <CodeType>PR</CodeType>
    </Code>
</Codes>

I'd like to be able to use a linq query to tell me if a code element has a codetype based on ID. This is what I've come up with so far. It works but it's ugly and I'd prefer to use dot notation if possible. Can anybody help me out?

public bool HasCodeType(string CodeType, string Code)
{
    var QueryResult = (from descendant in XMLdocument.Descendants("Code")
                       from type in descendant.Elements("CodeType")
                       where type != null &&
                             type.Value.Equals(CodeType)
                       select new { CID = descendant.Element("CodeID").Value }).Distinct();

    foreach (var result in QueryResult)
    {
        if (Code == result.CID)
            return true;
    }

    return false;
}

It's probably simplest to find the CodeType first, then go "up and down":

// Note camelCase for variable names, not PascalCase.
var query = document.Descendants("CodeType")
                    .Where(type => type.Value == codeType)
                    .Select(type => (string) type.Parent.Element("CodeID"))
                    .Where(id => id == null)
                    .Distinct();

The second Where clause is to avoid getting null values for CodeType elements with no sibling CodeID element.

If all you're doing with the query is checking for the presence of the given ID though, you don't need to go to all that trouble:

return document.Descendants("Code")
               .Any(code => (string) code.Element("CodeType") == codeType &&
                            (string) code.Element("CodeID") == codeId));

Really simple.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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