Namespace와 LINQ to XML


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



크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 And Comment 2
  1. BlogIcon cube 2009/01/22 09:42 address edit & del reply

    도움이 많이 됐어요! 항상 옆에 계시는 길버트님 헤헤

    • BlogIcon 길버트 2009/01/23 09:11 address edit & del

      Hello World!팀 잘하고 있죠?
      물어볼꺼 생기면 언제든 연락하라고~ ^^

prev · 1 ... · 286 · 287 · 288 · 289 · 290 · 291 · 292 · 293 · 294 ... · 836 · next