Gewusst wie: Ermitteln eines Elements mit einem bestimmten Attribut
Aktualisiert: November 2007
In diesem Thema wird gezeigt, wie Sie nach einem Element mit einem bestimmten Wert suchen können.
Beispiel
Das Beispiel zeigt die Suche nach dem Address-Element mit dem Type-Attribut und dem Wert "Billing".
In diesem Beispiel wird das XML-Dokument in XML-Beispieldatei: Typischer Auftrag (LINQ to XML) verwendet. XML-Beispieldatei: Typischer Auftrag (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
Dieser Code erzeugt die folgende Ausgabe:
<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>
Beachten Sie, dass von der Visual Basic-Version dieses Beispiels die Untergeordnete XML-Achseneigenschaft, die XML-Attribut Achseneigenschaft und die XML-Value-Eigenschaft verwendet werden.
Im folgenden Beispiel wird dieselbe Abfrage für XML in einem Namespace gezeigt. Weitere Informationen dazu finden Sie unter Arbeiten mit XML-Namespaces.
In diesem Beispiel wird das XML-Dokument in XML-Beispieldatei: Typischer Auftrag in einem Namespace verwendet. XML-Beispieldatei: Typischer Auftrag in einem Namespace.
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
Dieser Code erzeugt die folgende Ausgabe:
<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>
Siehe auch
Konzepte
Einfache Abfragen (LINQ to XML)
Übersicht über Standardabfrageoperatoren