我有以下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放到对象中。有人能给出一个解决方案吗?
发布于 2010-05-14 00:12:06
您的代码几乎是正确的。尝试一下这个细微的变化:
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 = ....
};https://stackoverflow.com/questions/2828336
复制相似问题