如何创建字典通过 LINQ to 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>
并且我有以下代码,我要在其中获取一个 Dictionary
对象,
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 获取到对象中。有人能提出解决方案吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的代码几乎是正确的。请尝试这个细微的变化:
我认为长
from ... select
语法在这里并没有多大帮助。我会使用这个稍微简单的代码:但是,您在示例代码中使用了匿名类型。如果您计划将此对象返回给调用者,则需要使用具体类型。
Your code is nearly correct. Try this slight variation instead:
I don't think the long
from ... select
syntax really helps much here. I'd use this slightly simpler code instead: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.