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"));
Dim root As XElement = XElement.Load("TestConfig.xml")
Dim tests As IEnumerable(Of XElement) = _
From el In root.<Test> _
Where el.<CommandLine>.Value = "Examp2.EXE" _
Select el
For Each el as XElement In tests
Console.WriteLine(el.@TestId)
Next
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"));
Imports <xmlns='http://www.adatum.com'>
Module Module1
Sub Main()
Dim root As XElement = XElement.Load("TestConfigInNamespace.xml")
Dim tests As IEnumerable(Of XElement) = _
From el In root.<Test> _
Where el.<CommandLine>.Value = "Examp2.EXE" _
Select el
For Each el As XElement In tests
Console.WriteLine(el.@TestId)
Next
End Sub
End Module
This code produces the following output:
0002
0006