HOW TO:尋找具有特定屬性的項目
這個主題顯示如何尋找其屬性具有特定值的項目。
範例
此範例顯示如何尋找其 Type 屬性具有 "Billing" 值的 Address 項目。
此範例使用下列 XML 文件:範例 XML 檔案:典型的採購訂單 (LINQ to XML)。
XElement root = XElement.Load("PurchaseOrder.xml");
IEnumerable<XElement> address =
from el in root.Elements("Address")
where (string)el.Attribute("Type") == "Billing"
select el;
foreach (XElement el in address)
Console.WriteLine(el);
Dim root As XElement = XElement.Load("PurchaseOrder.xml")
Dim address As IEnumerable(Of XElement) = _
From el In root.<Address> _
Where el.@Type = "Billing" _
Select el
For Each el As XElement In address
Console.WriteLine(el)
Next
此程式碼會產生下列輸出:
<Address Type="Billing">
<Name>Tai Yee</Name>
<Street>8 Oak Avenue</Street>
<City>Old Town</City>
<State>PA</State>
<Zip>95819</Zip>
<Country>USA</Country>
</Address>
請注意,這個範例的 Visual Basic 版本會使用 XML 子代軸屬性、XML 屬性軸屬性和 XML Value 屬性。
下列範例顯示命名空間中之 XML 的相同查詢。 如需詳細資訊,請參閱使用 XML 命名空間。
此範例使用下列 XML 文件:XML 範例檔:命名空間中的典型採購訂單。
XElement root = XElement.Load("PurchaseOrderInNamespace.xml");
XNamespace aw = "https://www.adventure-works.com";
IEnumerable<XElement> address =
from el in root.Elements(aw + "Address")
where (string)el.Attribute(aw + "Type") == "Billing"
select el;
foreach (XElement el in address)
Console.WriteLine(el);
Imports <xmlns:aw='https://www.adventure-works.com'>
Module Module1
Sub Main()
Dim root As XElement = XElement.Load("PurchaseOrderInNamespace.xml")
Dim address As IEnumerable(Of XElement) = _
From el In root.<aw:Address> _
Where el.@aw:Type = "Billing" _
Select el
For Each el As XElement In address
Console.WriteLine(el)
Next
End Sub
End Module
這個程式碼產生下列輸出:
<aw:Address aw:Type="Billing" xmlns:aw="https://www.adventure-works.com">
<aw:Name>Tai Yee</aw:Name>
<aw:Street>8 Oak Avenue</aw:Street>
<aw:City>Old Town</aw:City>
<aw:State>PA</aw:State>
<aw:Zip>95819</aw:Zip>
<aw:Country>USA</aw:Country>
</aw:Address>