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
CodeTypefirst, then go “up and down”:The second
Whereclause is to avoid gettingnullvalues forCodeTypeelements with no siblingCodeIDelement.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:
Really simple.