我有以下 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 获取到对象中。谁能提出解决方案?
最佳答案
您的代码几乎是正确的。试试这种细微的变化:
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 = ....
};
关于c# - 如何通过 LINQ to XML 创建 Dictionary<int, string>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2828336/