특정 특성으로 요소를 찾는 방법(LINQ to XML)

이 문서에서는 특성에 특정 값이 있는 요소를 찾는 방법에 대한 예를 제공합니다.

예: 특성이 특정 값을 갖는 요소 찾기

다음 예에서는 값이 "Billing"인 Type 특성이 있는 Address 요소를 찾는 방법을 보여 줍니다. 이 예에서는 XML 문서 샘플 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>

예: 네임스페이스에 있는 XML의 요소 찾기

다음 예에서는 동일한 쿼리를 보여 주지만 네임스페이스에 있는 XML에 대한 것입니다. XML 문서 샘플 XML 파일: 네임스페이스의 일반적인 구매 주문서를 사용합니다.

네임스페이스에 대한 자세한 내용은 네임스페이스 개요를 참조하세요.

XElement root = XElement.Load("PurchaseOrderInNamespace.xml");
XNamespace aw = "http://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='http://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="http://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>

참고 항목