如何:查找具有特定子元素的元素
更新:November 2007
本主题演示如何查找特定元素,该特定元素包含具有特定值的子元素。
示例
示例查找 Test 元素,该元素包含具有值为“Examp2.EXE”的 CommandLine 子元素。
本示例使用下面的 XML 文档:示例 XML 文件:测试配置 (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
此代码生成以下输出:
0002
0006
请注意,此示例的 Visual Basic 版本使用“XML 子轴”属性 (Property)、“XML 属性 (Attribute) 轴”属性 (Property)和“XML 值”属性 (Property)。
下面的示例演示如何对命名空间中的 XML 进行同样的查询。有关更多信息,请参见使用 XML 命名空间。
本示例使用下面的 XML 文档:示例 XML 文件:命名空间中的测试配置.
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
此代码生成以下输出:
0002
0006