2010-05-13 43 views
3

我有以下XML:如何通过LINQ创建词典<int, string>到XML?

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

和我有下面的代码,我得到一个Dictionary<int, string>()对象为

myObject.FootNotes 

使每一行是键/值对

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

该代码是_almost_正确的,除了'(从fn in和尾部')'。您在编辑之前提供的示例指出了这一点。你应该恢复最后一次编辑,所以我可以选择这个作为正确的答案 – DaveDev 2010-05-13 16:25:47

+0

@DaveDev:我其实现在也添加了:) – 2010-05-13 16:27:41