加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何添加XML文件并将键值对读入字典?

发布时间:2020-12-16 01:56:45 所属栏目:百科 来源:网络整理
导读:参见英文答案 How to serialize/deserialize to `Dictionaryint,string` from custom XML not using XElement?????????????????????????????????????10个 我对编程很新.我试图添加一个XML文件,以存储一些映射.我想在字典中准备好这些键值对.以下是我想的XML
参见英文答案 > How to serialize/deserialize to `Dictionary<int,string>` from custom XML not using XElement?????????????????????????????????????10个
我对编程很新.我试图添加一个XML文件,以存储一些映射.我想在字典中准备好这些键值对.以下是我想的XML格式:

<?xml version="1.0" encoding="utf-8" ?>
<Map>
  <add keyword="keyword1" replaceWith="replaceMe1"/>
  <add keyword="keyword2" replaceWith="replaceMe2"/>  
</Map>

你能告诉我格式是否正确吗?如果是,我怎么读到我的C#字典?

解决方法

您可以使用LINQ to XML:

var xdoc = XDocument.Load(path_to_xml);
var map = xdoc.Root.Elements()
                   .ToDictionary(a => (string)a.Attribute("keyword"),a => (string)a.Attribute("replaceWith"));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读