将XML读取到字典 [英] Reading XML to a Dictionary
本文介绍了将XML读取到字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要阅读一个XML文件,我读了几本指南,只有我不明白的奇怪的单词(比如节点,XML验证等)才感到困惑。
所以,请问我可以通过吗?
I need to read a XML file, I read few guides and I only got confused from weird words that I don't understand (such as nodes, XML validation etc.). So, could you please walk me through?
我有一个以这种格式写的XML文件:
I have a XML file which is written in this format:
<database>
<def number="1" name="one"/>
<def number="2" name="two"/>
</database>
我想将其存储在字典中,请告诉我如何做到这一点。
谢谢。
I want to store it in a dictionary, please show me how can I do it. Thanks.
哦,对不起,如果这个问题太基础和不合适。
Oh, and I'm sorry if this question is too basic and inappropriate.
推荐答案
var data = XElement.Parse(xml)
.Elements("def")
.ToDictionary(
el => (int)el.Attribute("number"),
el => (string)el.Attribute("name")
);
This:
- 将xml解析成一个
XElement
(从< database>
开始) - 迭代
< def ...>
元素 - 使用
@number
作为密钥(解释为int
),而@name
as值(作为字符串) - 将此字典分配给
数据
,它隐式键入为Dictionary< int,string>
- parses the xml into an
XElement
(starting at<database>
) - iterates over the
<def ...>
elements - forms a dictionary, using
@number
as the key (interpreting as anint
), and@name
as the value (as a string) - assigns this dictionary to
data
, which is implicitly typed asDictionary<int,string>
这篇关于将XML读取到字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文