Share via


How to: Find an Element with a Specific Attribute

This topic shows how to find an element that has an attribute that has a specific value.

Example

The example shows how to find the Address element that has a Type attribute with a value of "Billing".

This example uses the following XML document: Sample XML File: Typical Purchase Order (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

This code produces the following output:

<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>

Note that the Visual Basic version of this example uses the XML Child axis property, the XML Attribute axis property, and the XML Value property.

The following example shows the same query for XML that is in a namespace. For more information, see Working with XML Namespaces.

This example uses the following XML document: Sample XML File: Typical Purchase Order in a 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

This code produces the following output:

<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>

See Also

Reference

Attribute

Elements

Concepts

Basic Queries (LINQ to XML)

Standard Query Operators Overview

Projection Operations