Converting Request.InputStream to a string - Part 2
Preceded by: Converting Request.InputStream to a string - Part 1 A natural extension to this, is the ability to transform the InputStream (basically the POST data) into an XMLDocument and then parse it.
The first step is to convert it into an XML Document:
using System;
using System.IO;
using System.Text;
using System.Web;
using System.Xml;
using System.Collections.Generic;
class RequestToInputStream
{
// Constructor and previous code omitted for brevity
private XmlDocument PrepareXmlDocument()
{
XmlDocument doc = new XmlDocument();
doc.InnerXml = RequestInputStreamToString(Request.InputStream);
return doc;
}
private List<Dictionary<string, string>> NodeAttributesCollection(XmlDocument Document, string XPathExpression)
{
List<Dictionary<string, string>> nodesCollection = new List<Dictionary<string, string>>();
foreach (XmlNode n in Document.SelectNodes(XPathExpression))
{
nodesCollection.Add(NodeAttributes(n));
}
return nodesCollection;
}
private Dictionary<string, string> NodeAttributes(XmlDocument Document, string XPathExpression)
{
return NodeAttributes(Document.SelectSingleNode(XPathExpression));
}
private Dictionary<string, string> NodeAttributes(XmlNode node)
{
Dictionary<string, string> attributes = new Dictionary<string, string>();
if ((node != null) && (node.Attributes.Count != 0))
{
foreach (XmlAttribute a in node.Attributes)
{
attributes.Add(a.Name, a.Value);
}
}
return attributes;
}
private string RequestInputStreamToString(stream s)
{
// code as previously
}
}
Two new helper functions, NodeAttributes and NodeAttributeCollection, the purpose of each being:
- NodeAttributes - When passed an XPath expression that resolves to a single node (such as "entity" in the specimen below) returns a generic Dictionary of strings which contains pairs of attribute names and values.
- NodeAttributesCollection - When passed an XPath expression that resolves to more than one node (such as "entityMulti" in the specimen below) returns a collection of Dictionaries (as would be returned by NodeAttributes
Specimen XML:< entity name="entityName" otherValue="otherValue">< entityMulti name="entityMulti1" />< entityMulti name="entityMulti2" />< entityMulti name="entityMulti3" />< /entity>