Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何创建字典并在c中存储值#_C#_Xml_Dictionary - Fatal编程技术网

C# 如何创建字典并在c中存储值#

C# 如何创建字典并在c中存储值#,c#,xml,dictionary,C#,Xml,Dictionary,我想为以下xml创建一个字典: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <groups> <group> <data>Open</data> <aggregation>5</aggregation> </group> </grou

我想为以下xml创建一个字典:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <groups>
        <group>
            <data>Open</data>
            <aggregation>5</aggregation>
        </group>
    </groups>

我没有得到想要的回应。请指出我哪里做错了。谢谢使用XElement和LINQ to XML。 你应该加上

using System.Xml;
using System.Xml.Linq;
在你的代码之上。然后使用以下命令

string xml = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><groups><group><data>Open</data><aggregation>5</aggregation></group></groups>";

XElement xe =  XElement.Parse(xml);

Dictionary<string,string> d =
xe.Elements("group")
.ToDictionary 
(
    x=>(string)x.Element("data"),      //Key Selector
    z=>(string)z.Element("aggregation")//Value Selector
);
stringxml=@“Open5”;
XElement xe=XElement.Parse(xml);
字典d=
xe.元素(“组”)
.ToDictionary
(
x=>(字符串)x.Element(“数据”),//键选择器
z=>(字符串)z.Element(“聚合”)//值选择器
);
有些人可能还建议使用XDocument,因为您提供了带有声明等的完全限定xml:

XDocument xd = XDocument.Parse(xml);

Dictionary<string,string> d =   
xd.Root.Elements("group")
.ToDictionary 
(
    x=>(string)x.Element("data"),      //Key Selector
    z=>(string)z.Element("aggregation")//Value Selector
);
XDocument xd=XDocument.Parse(xml);
字典d=
xd.Root.Elements(“组”)
.ToDictionary
(
x=>(字符串)x.Element(“数据”),//键选择器
z=>(字符串)z.Element(“聚合”)//值选择器
);

可能重复@I4V至少这一个得到了答案。不要重新发布问题,您可以编辑以改进它们。这一个比前一个更清晰,所以这一个应该站着。@HenkHolterman同意你应该先声明
xe
。我会使用
(string)XElement
显式强制转换,而不是
Value
属性。@MarcinJuraszek我在LINQPad的代码中声明了它,但显然我忘了将它粘贴到这里:)。我承认我不知道我可以用石膏。。。你认为它比使用值好吗?如果使用
字典d=…
@jyparask
(string)XElement
在找不到元素时不会抛出
NullReferenceException
。@jyparask
(int)XElement
将为
null
元素抛出异常,
(int?)XElement
可以正常工作。您可以找到可以将
XElement
强制转换为on的所有支持类型的列表
XDocument xd = XDocument.Parse(xml);

Dictionary<string,string> d =   
xd.Root.Elements("group")
.ToDictionary 
(
    x=>(string)x.Element("data"),      //Key Selector
    z=>(string)z.Element("aggregation")//Value Selector
);