I make a request to a service and receive an xml response as shown below. However, I'm trying to store the response values in a Dictionary (or store the values returned in variables) and I can't seem to make it work.
Any help would be greatly appreciated.
xml response received:
<?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>
c# code:
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;
}
Use this:
using System.Xml.Linq; // required namespace for linq-to-xml
/* ... get xml into 'body' string */
XDocument doc = XDocument.Parse(body);
to load the XML file into an XDocument
object.
Then, you can use Linq-to-XML to parse the XML and ToDictionary
extension method to create a key / value pair for each attribue of the XML:
var output = doc.Element("ncresponse")
.Attributes()
.Select(c => new {
Key = c.Name,
Value = c.Value
})
.ToDictionary(k => k.Key, v => v.Value);
It seems I overcomplicated things (credit goes to @KyleW). This:
var output = doc.Element("ncresponse")
.Attributes()
.ToDictionary(k => k.Name, v => v.Value);
is equivalent to the inital linq query. Select
is only necessary only in case some pre-processing of the values placed in the dictionary is required.
Ouput:
[0] = {[NCERRORPLUS, !]}
[1] = {[BRAND, ABC]}
[2] = {[PM, CC]}
... etc