Learner
Learner

Reputation: 4751

LINQ statement to select the element which is deep inside the XML structure

I have XML which looks something like this:

<?xml version="1.0" encoding="utf-8"?>
     <University>
          <Colleges>
            <College>
              <Id> Cambridge </Id>
              <Dept>
                <Id> Arts</Id>
              </Dept>
            </College>
            <College>
              <Id> Oxford</Id>
              <Dept>
                <Id> Philosophy </Id>
              </Dept>
            </College>
          </Colleges>
        </University>

I want to return the College based on the ID. In another scenario, I want to written just Id of the College.

I do not understand how to write LINQ statement to read Id directly. I can use Descendants() at every stage. But how to select the element which is deep inside the XML structure?

Upvotes: 1

Views: 998

Answers (2)

Steve B
Steve B

Reputation: 37660

Maybe you should use XPath. The syntax will be simpler than a pure Linq query :

using  System.Xml;
using  System.Xml.XPath;
...

public foo()
{
    XElement yourNode = XElement.Parse(yourstring);
    XElement college = root.XPathSelectElement("//College[Id='Oxford']");
}

If you can have College node at several position in the structure, the XPAth query /University/Colleges/College[Id='OxFord'] will avoid conflicting issue.

Upvotes: 4

KV Prajapati
KV Prajapati

Reputation: 94625

LINQ-XML,

XDocument doc = XDocument.Parse(xmlStr);
var results = doc.Root.Descendants("College")
              .Where(ele => ele.Element("Id").Value.Trim() == "Oxford");

Upvotes: 3

Related Questions