将 XML 读取到字典中
我需要将 XML 文件读取到字典中。
我读了一些指南,只是对我不理解的奇怪单词(例如节点、XML 验证等)感到困惑。 那么,您能帮我介绍一下吗?
我有一个以这种格式编写的 XML 文件:
<database>
<def number="1" name="one"/>
<def number="2" name="two"/>
</database>
如前所述,我想将其存储在字典中。我该怎么办呢?
I need to read an XML file to a dictionary.
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?
I have an XML file which is written in this format:
<database>
<def number="1" name="one"/>
<def number="2" name="two"/>
</database>
As mentioned, I want to store it in a dictionary. How would I go about that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此操作:
XElement
(从
开始)
元素@number
作为键(解释为int
),使用@name
作为值(作为字符串)数据
,隐式类型为Dictionary
This:
XElement
(starting at<database>
)<def ...>
elements@number
as the key (interpreting as anint
), and@name
as the value (as a string)data
, which is implicitly typed asDictionary<int,string>
你的问题很基本,但也并非不恰当。不用担心。我会解释你应该做什么。
首先,您必须加载此 XML 文件(如果它在磁盘上)。否则你不需要这一步
到这里,你得到:
然后你必须获得所有 def 元素的列表:
到这里,你得到:
现在,你应该得到list(defs 中的每个 def):
从每个 def 中提取信息的代码是:
现在您已经有了号码和姓名,只需将其添加到字典中即可。
希望有帮助。
Your question is basic, but not inappropriate. Don't worry. I'll explain what you should do.
first you have to load this XML file (if it's on the disk). Otherwise you don't need this step
up to here, you got:
Then you have to get a list of all def elements:
up to here, you got:
Now, you should get each item of the list (each def in defs):
the code to extract information from each def is:
Now that you have your number and name, just add it to your dictionary.
Hope that helps.