다음을 통해 공유


방법: 부모의 특성 찾기(XPath-LINQ to XML)

이 항목에서는 부모 요소를 탐색하고 부모 요소의 특성을 찾는 방법을 보여 줍니다.

XPath 식은 다음과 같습니다.

../@id

예제

이 예제에서는 먼저 Author 요소를 찾은 다음 부모 요소의 id 특성을 찾습니다.

이 예제에서는 XML 문서로 샘플 XML 파일: 책(LINQ to XML)을 사용합니다.

XDocument books = XDocument.Load("Books.xml");

XElement author = 
    books
    .Root
    .Element("Book")
    .Element("Author");

// LINQ to XML query
XAttribute att1 =
    author
    .Parent
    .Attribute("id");

// XPath expression
XAttribute att2 = ((IEnumerable)author.XPathEvaluate("../@id")).Cast<XAttribute>().First();

if (att1 == att2)
    Console.WriteLine("Results are identical");
else
    Console.WriteLine("Results differ");
Console.WriteLine(att1);
Dim books As XDocument = XDocument.Load("Books.xml")
Dim author As XElement = books.Root.<Book>.<Author>.FirstOrDefault()

' LINQ to XML query
Dim att1 As XAttribute = author.Parent.Attribute("id")

' XPath expression
Dim att2 As XAttribute = DirectCast(author.XPathEvaluate("../@id"),  _
    IEnumerable).Cast(Of XAttribute)().First()

If att1 Is att2 Then
    Console.WriteLine("Results are identical")
Else
    Console.WriteLine("Results differ")
End If
Console.WriteLine(att1)

이 예제는 다음과 같이 출력됩니다.

Results are identical
id="bk101"

참고 항목

개념

XPath 사용자에 대한 LINQ to XML