我有一个像这样的XML文件:
<APICollection><API name="myapiName" message="myAPIMessage" /></APICollection>
当我尝试在这样的字典中阅读时:
Dictionary<string,string> apiMap = new Dictionary<string,string>();
XDocument xdoc = XDocument.Load(path);
apiMap = xdoc.Root.Elements()
.ToDictionary(a => (string)a.Attribute("apiName"), a => (string)a.Attribute("apiMessage"));
一切都很好。但是,如果我有多个具有相同键(名称)的条目,我会得到一个像这样的通用异常:
An item with the same key has already been added.
我想知道如何修改错误消息以至少多次提供哪个密钥。有人可以帮忙吗?
谢谢,
Harit
答案 0 :(得分:1)
我建议不要直接创建字典,而是首先检查这样的重复键:
XDocument xdoc = XDocument.Load(path);
var apiMap = xdoc.Root.Elements()
.Select(a => new
{
ApiName = (string)a.Attribute("apiName"),
ApiMessage = (string)a.Attribute("apiMessage")
});
var duplicateKeys = (from x in apiMap
group x by x.ApiName into g
select new { ApiName = g.Key, Cnt = g.Count() })
.Where(x => x.Cnt > 1)
.Select(x => x.ApiName);
if (duplicateKeys.Count() > 0)
throw new InvalidOperationException("The following keys are present more than once: "
+ string.Join(", ", duplicateKeys));
Dictionary<string, string> apiMapDict =
apiMap.ToDictionary(a => a.ApiName, a => a.ApiMessage);
请注意,我已更改了示例中的属性名称(&#34;名称&#34;,&#34;消息&#34;)和代码示例之间存在差异的代码(&#34; apiName&#34;,&#34; apiMessage&#34;)。
答案 1 :(得分:0)
Attribute
方法采用属性名称,而不是值。用属性名称替换值。还可以使用Value
属性来获取属性的值。
即使这样做,用作关键字的属性值也必须是唯一的 - 因为您使用的是Dictionary<T,T>
Dictionary<string,string> apiMap = new Dictionary<string,string>();
XDocument xdoc = XDocument.Load(path);
apiMap = xdoc.Root.Elements()
.ToDictionary(a => a.Attribute("name").Value
, a => a.Attribute("message").Value);
答案 2 :(得分:0)
试试这个:
var xmlDocument = XDocument.Load(path);
var values = xmlDocument
.Descendants("API")
.GroupBy(x => (string)x.Attribute("name"))
.ToDictionary(x => x.Key,
x => x.Select(p => (string)p.Attribute("message").ToList());
这将给你一个Dictionary<string, List<string>>
,键是名称,值是属于Api名称的消息。如果你只想要字典,那么改变代码如下:
var values = xmlDocument
.Descendants("API")
.GroupBy(x => (string)x.Attribute("name"))
.ToDictionary(x => x.Key,
x => (string)x.First().Attribute("message"));