2010-05-13 4 views
3

나는 다음과 같은 XML을 가지고LINQ to XML을 통해 사전 <int, string>을 만드는 방법은 무엇입니까?

<FootNotes> 
    <Line id="10306" reference="*"></Line> 
    <Line id="10308" reference="**"></Line> 
    <Line id="10309" reference="***"></Line> 
    <Line id="10310" reference="****"></Line> 
    <Line id="10311" reference="+"></Line> 
</FootNotes> 

나는 내가 그렇게 각 라인은 키/값 쌍

것을

myObject.FootNotes 

Dictionary<int, string>() 개체를 얻을 수있어 다음과 같은 코드가 있습니다

var doc = XElement.Parse(xmlString); 

var myObject = new 
    { 
     FootNotes = (from fn in doc 
         .Elements("FootNotes") 
         .Elements("Line") 
         .ToDictionary 
         (
         column => (int) column.Attribute("id"), 
         column => (string) column.Attribute("reference") 
         ) 
       ) 
    }; 

XML에서 개체로 가져 오는 방법을 잘 모르겠습니다. 누구든지 해결책을 제안 할 수 있습니까?

답변

6

코드가 거의 정확합니다. 대신 약간의 변화를 시도 :

FootNotes = (from fn in doc.Elements("FootNotes") 
          .Elements("Line") 
      select fn).ToDictionary(
       column => (int)column.Attribute("id"), 
       column => (string)column.Attribute("reference") 
      ) 

나는 긴 from ... select 구문이 정말 많은 여기에 도움이 생각하지 않습니다. 이 약간 간단한 코드를 대신 사용하겠습니다.

Footnotes = doc.Descendants("Line").ToDictionary(
       e => (int)e.Attribute("id"), 
       e => (string)e.Attribute("reference") 
      ) 

그러나 예제 코드에서는 익명 형식을 사용하고 있습니다. 이 객체를 호출자에게 반환하려는 경우 구체적인 유형을 사용해야합니다.

var myObject = new SomeConcreteType 
    { 
     Footnotes = .... 
    }; 
+0

'(fn 인'과 후행 인')을 제외하고 코드는 _ 정확합니다. 편집하기 전에 제공 한 샘플에서이를 지적했습니다. 마지막 편집을 되돌려서 정답으로 선택할 수 있도록 – DaveDev

+0

@DaveDev : 실제로 추가했습니다. :) –

관련 문제