Silverlight/Lecture

Namespace와 LINQ to XML

길버트리 2008. 7. 24. 22:13
<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             x:Class="ButtonStyleSample.App"
             xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows"
             >
    <vsm:Application.Resources>
         <Style x:Key="myButtonStyle" TargetType="Button">
             ...생략
         </Style>
         <Style x:Key="yourButtonStyle" TargetType="Button">
             ...생략
         </Style>
         <Style x:Key="herButtonStyle" TargetType="Button">
             ...생략
         </Style>
         <Style x:Key="hisButtonStyle" TargetType="Button">
             ...생략
         </Style>
    </vsm:Application.Resources>
</Application>

string xml에 위의 내용이 들어있다고 가정하고,

XDocument xDoc = XDocument.Parse(xml);

위와 같이 xDoc을 준비해 놓고,

XML데이터에서 Style을 돌면서 x:Key의 Value값만 쏙쏙 뽑아내는 LINQ구문을 작성한다면
어떻게 하시겠습니까?


오답

첨엔 막연히 이렇게 해봤습니다.

var result = from c in xDoc.Descendants("Style")
                select (string)c.Attribute("x:Key").Value;

네, 에러가 납니다.
Attribute의 이름에는 콜론(:)을 추가할 수 없습니다.

Attribute메서드의 파라미터는 XName이구요.
XName을 생성할 때 콜론(:)이 들어간 문자열을 허용하지 않기 때문입니다.

정답

XNamespace x = "http://schemas.microsoft.com/winfx/2006/xaml";
var result = from c in xDoc.Descendants("Style")
                select (string)c.Attribute(x + "Key").Value;

XNamespace + string이 XName이 되도록 연산기호 +에 대해
오퍼레이트 오버라이딩이 잘 되어있더라구요.

x + "Key" 이런 식으로 사용하는 것은 썩 직관적이지 않아서 맘에 안드는데,
알고 나니까 잘 쓸 수는 있겠더라구요. ^^

하지만 역시 LINQ는 쓰면 쓸수록 편한 것 같습니다.

Enjoy your LINQ!