1

I'm new to LINQ and am attempting to query an XML file by attribute and a descendant element value.

Here's a snip of my XML:

<redirurl>
    <exceptionList state="FL">
        <exception>
            <plancode>ZZ</plancode>
            <url>https://zzzz.com</url>
        </exception>
    </exceptionList>    
    <exceptionList state="NC">
        <exception>
            <plancode>AA</plancode>
            <url>https://aaaa.com</url>
        </exception>
        <exception>
            <plancode>BB</plancode>
            <url>https://bbbb.com</url>
        </exception>
    </exceptionList>
</redirurl>

I'm trying to retrieve the value for url by state and plancode. For example, if the exceptionList state attribute = "NC" and the plancode = "BB", I want to get the url of "https://bbbb.com".

Here's my code:

var xmlFilePath = "myFilePathHere";
XElement xelement = XElement.Load(xmlFilePath );

IEnumerable<XElement> urlAddress = from el in xelement.Elements("exceptionList")
                                   where (string)el.Attribute("state") == "NC"
                                   && (string)el.Element("exception").Element("plancode") == "BB"
                                   select el;

I can't get the query right to save my life. If I omit the third line of the query (plancode line), I get the entire exceptionList node as a result. I suppose I could loop through it to get the plancode, but that doesn't seem like the right thing to do. The query as is does not return results. I've spent about 10 hours on this, doing tutorials and looking at code examples, but I'm just not getting it. Can someone advise what I'm missing? Thanks in advance.

1 Answer 1

1

Here is a Linq sequence that does as you ask:

XDocument doc = XDocument.Parse("<redirurl><exceptionList state=\"FL\"><exception><plancode>ZZ</plancode><url>https:////zzzz.com</url></exception></exceptionList><exceptionList state=\"NC\"><exception><plancode>AA</plancode><url>https:////aaaa.com</url></exception><exception><plancode>BB</plancode><url>https:////bbbb.com</url></exception></exceptionList></redirurl>");

            var urlIWant = doc.Root.Descendants("exceptionList").Where(x => x.Attribute("state").Value == "NC").FirstOrDefault()
                .Descendants("exception").Where(z => z.Descendants("plancode").FirstOrDefault().Value == "BB")
                    .FirstOrDefault().Descendants("url").FirstOrDefault().Value;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Works perfectly and I understand the query now!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.