HOW TO:篩選選擇性的項目
有時候即使您不確定項目是否存在於 XML 文件中,您都會想要針對該項目進行篩選。 搜尋應該會執行,因此,如果特定的項目沒有子項目,您就不會篩選該項目來觸發 Null 參考例外狀況。 在下列範例中,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