问题
I have the following 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")
)
)
};
I am unsure how to get this from the XML into the object though. Can anyone suggest a solution?
回答1:
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 = ....
};
来源:https://stackoverflow.com/questions/2828336/how-to-create-dictionaryint-string-via-linq-to-xml