How to: Find an Element with a Specific Child Element

This topic shows how to find a particular element that has a child element with a specific value.

Example

The example finds the Test element that has a CommandLine child element with the value of "Examp2.EXE".

This example uses the following XML document: Sample XML File: Test Configuration (LINQ to XML).

XElement root = XElement.Load("TestConfig.xml");
IEnumerable<XElement> tests =
    from el in root.Elements("Test")
    where (string)el.Element("CommandLine") == "Examp2.EXE"
    select el;
foreach (XElement el in tests)
    Console.WriteLine((string)el.Attribute("TestId"));

This code produces the following output:

0002
0006

Note that the Visual Basic version of this example uses the XML Child axis property, the XML Attribute axis property, and the XML Value property.

The following example shows the same query for XML that is in a namespace. For more information, see Working with XML Namespaces.

This example uses the following XML document: Sample XML File: Test Configuration in a Namespace.

XElement root = XElement.Load("TestConfigInNamespace.xml");
XNamespace ad = "http://www.adatum.com";
IEnumerable<XElement> tests =
    from el in root.Elements(ad + "Test")
    where (string)el.Element(ad + "CommandLine") == "Examp2.EXE"
    select el;
foreach (XElement el in tests)
    Console.WriteLine((string)el.Attribute("TestId"));

This code produces the following output:

0002
0006

See Also




Build Date:

2012-08-02
Show: