更新:November 2007
有时,尽管不能确定某个元素是否存在于 XML 文档中,您还是会尝试筛选该元素。应当执行搜索,这样如果特定元素没有子元素,就不会因为筛选它而触发空引用异常。在下面的示例中,Child5 元素没有 Type 子元素,但是查询仍可以正确执行。
示例
本示例使用 Elements 扩展方法。
XElement root = XElement.Parse(@"<Root>
<Child1>
<Text>Child One Text</Text>
<Type Value=""Yes""/>
</Child1>
<Child2>
<Text>Child Two Text</Text>
<Type Value=""Yes""/>
</Child2>
<Child3>
<Text>Child Three Text</Text>
<Type Value=""No""/>
</Child3>
<Child4>
<Text>Child Four Text</Text>
<Type Value=""Yes""/>
</Child4>
<Child5>
<Text>Child Five Text</Text>
</Child5>
</Root>");
var cList =
from typeElement in root.Elements().Elements("Type")
where (string)typeElement.Attribute("Value") == "Yes"
select (string)typeElement.Parent.Element("Text");
foreach(string str in cList)
Console.WriteLine(str);
Dim root As XElement = _
<Root>
<Child1>
<Text>Child One Text</Text>
<Type Value="Yes"/>
</Child1>
<Child2>
<Text>Child Two Text</Text>
<Type Value="Yes"/>
</Child2>
<Child3>
<Text>Child Three Text</Text>
<Type Value="No"/>
</Child3>
<Child4>
<Text>Child Four Text</Text>
<Type Value="Yes"/>
</Child4>
<Child5>
<Text>Child Five Text</Text>
</Child5>
</Root>
Dim cList As IEnumerable(Of String) = _
From typeElement In root.Elements().<Type> _
Where typeElement.@Value = "Yes" _
Select typeElement.Parent.<Text>.Value
Dim str As String
For Each str In cList
Console.WriteLine(str)
Next
此代码生成以下输出:
Child One Text
Child Two Text
Child Four Text
下面的示例演示如何对命名空间中的 XML 进行同样的查询。有关更多信息,请参见使用 XML 命名空间。
XElement root = XElement.Parse(@"<Root xmlns='http://www.adatum.com'>
<Child1>
<Text>Child One Text</Text>
<Type Value=""Yes""/>
</Child1>
<Child2>
<Text>Child Two Text</Text>
<Type Value=""Yes""/>
</Child2>
<Child3>
<Text>Child Three Text</Text>
<Type Value=""No""/>
</Child3>
<Child4>
<Text>Child Four Text</Text>
<Type Value=""Yes""/>
</Child4>
<Child5>
<Text>Child Five Text</Text>
</Child5>
</Root>");
XNamespace ad = "http://www.adatum.com";
var cList =
from typeElement in root.Elements().Elements(ad + "Type")
where (string)typeElement.Attribute("Value") == "Yes"
select (string)typeElement.Parent.Element(ad + "Text");
foreach (string str in cList)
Console.WriteLine(str);
Imports <xmlns='http://www.adatum.com'>
Module Module1
Sub Main()
Dim root As XElement = _
<Root>
<Child1>
<Text>Child One Text</Text>
<Type Value="Yes"/>
</Child1>
<Child2>
<Text>Child Two Text</Text>
<Type Value="Yes"/>
</Child2>
<Child3>
<Text>Child Three Text</Text>
<Type Value="No"/>
</Child3>
<Child4>
<Text>Child Four Text</Text>
<Type Value="Yes"/>
</Child4>
<Child5>
<Text>Child Five Text</Text>
</Child5>
</Root>
Dim cList As IEnumerable(Of String) = _
From typeElement In root.Elements().<Type> _
Where typeElement.@Value = "Yes" _
Select typeElement.Parent.<Text>.Value
Dim str As String
For Each str In cList
Console.WriteLine(str)
Next
End Sub
End Module
此代码生成以下输出:
Child One Text
Child Two Text
Child Four Text