如何创建字典< INT,串>通过LINQ到XML?
我有下面的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>
和我有下面的代码,我得到一个词典<整型,字符串>()
对象为
and I have the following code where I'm to get a Dictionary<int, string>()
object into
myObject.FootNotes
,使每一行是一个键/值对
so that each Line is a Key/Value pair
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进入对象这虽然。任何人都可以提出一个解决方案?
I am unsure how to get this from the XML into the object though. Can anyone suggest a solution?
您的代码几乎是正确的。试试这个微小的变化,而不是:
Your code is nearly correct. Try this slight variation instead:
FootNotes = (from fn in doc.Elements("FootNotes")
.Elements("Line")
select fn).ToDictionary(
column => (int)column.Attribute("id"),
column => (string)column.Attribute("reference")
)
我不认为从长远从...选择
语法真的帮助很多在这里。我会用这个稍微简单的代码,而不是:
I don't think the long from ... select
syntax really helps much here. I'd use this slightly simpler code instead:
Footnotes = doc.Descendants("Line").ToDictionary(
e => (int)e.Attribute("id"),
e => (string)e.Attribute("reference")
)
不过你使用在你的示例代码匿名类型。您需要使用,如果你打算到这个对象返回给调用者的具体类型。
However you are using an anonymous type in your example code. You need to use a concrete type if you are planning to return this object to the caller.
var myObject = new SomeConcreteType
{
Footnotes = ....
};