将Xml文档转换为C#Dictionary

Bha*_*hav 0 c# xml xmldocument dictionary httpwebresponse

我向服务发出请求并收到xml响应,如下所示.但是,我正在尝试将响应值存储在Dictionary中(或存储变量中返回的值),而我似乎无法使其工作.

任何帮助将不胜感激.

收到的xml回复:

<?xml version="1.0"?>
<ncresponse NCERRORPLUS="!" BRAND="ABC" PM="CC" currency="GBP" amount="10" STATUS="9" ACCEPTANCE="test123" NCERROR="0" NCSTATUS="0" PAYID="39409494" orderID="92E5CE91">
</ncresponse>
Run Code Online (Sandbox Code Playgroud)

c#代码:

        try
        {
            // Write data
            using (Stream postStream = request.GetRequestStream())
            {
                postStream.Write(byteData, 0, byteData.Length);
            }

            // Get response
            Dictionary<string, string> respValues = new Dictionary<string, string>();
            try
            {
                string body = String.Empty;

                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    // Get the response stream
                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("iso-8859-1"));
                    body += reader.ReadToEnd();
                }

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(body);

                XmlNodeList list = xmlDoc.GetElementsByTagName("ncresponse");
                string xmlResponse = list[0].InnerText;
            }
            catch (WebException wex)
            {
                throw;
            }
Run Code Online (Sandbox Code Playgroud)

Gio*_*sos 7

用这个:

using System.Xml.Linq;  // required namespace for linq-to-xml
/* ... get xml into 'body' string */
XDocument doc = XDocument.Parse(body);
Run Code Online (Sandbox Code Playgroud)

将XML文件加载到XDocument对象中.

然后,您可以使用Linq-to-XML来解析XML和ToDictionary扩展方法,以便为XML的每个属性创建一个键/值对:

 var output = doc.Element("ncresponse")
                 .Attributes()          
                 .Select(c => new {
                     Key = c.Name,
                     Value = c.Value
                  })
                 .ToDictionary(k => k.Key, v => v.Value);
Run Code Online (Sandbox Code Playgroud)

看来我的事情过于复杂(归功于@KyleW).这个:

 var output = doc.Element("ncresponse")
                 .Attributes()          
                 .ToDictionary(k => k.Name, v => v.Value);
Run Code Online (Sandbox Code Playgroud)

相当于初始linq查询.Select只有在需要对字典中的值进行一些预处理时才需要.

输出继电器:

[0] = {[NCERRORPLUS, !]}
[1] = {[BRAND, ABC]}
[2] = {[PM, CC]}
... etc
Run Code Online (Sandbox Code Playgroud)