I have got a requirement where business people would be uploading the xml files (not more than 25 file) as multimedia components and we need to expose them as JSON. I started on the POC and after a bit of trial and error I am able to achieve it as below.
Is this approach achievable in Prod environment? As i am doubtful that It might cause an issue (memory leaks, etc) in an environment where the WCM is used heavily and performance is the highest priority. I am getting this thought seeing memory stream and xml files of sizes around 2MB.
I am confused in deciding the approach even though the below is working because I am fairly new to these kind of stream objects.
public void Transform(Engine engine, Package package)
{
try
{
Initialize(engine, package);
Item componentItem = Package.GetByType(ContentType.Component);
Component component = engine.GetObject(componentItem) as Component;
XmlDocument doc = new XmlDocument();
using (MemoryStream memoryStream = new MemoryStream())
{
BinaryContent binary = component.BinaryContent;
binary.WriteToStream(memoryStream);
xmlDoc.Load(memoryStream);
memoryStream.Close();
}
string jsonoutput = new JavaScriptSerializer().Serialize(GetXmlValues(XElement.Parse(doc.OuterXml)));
package.PushItem(Package.OutputName, Package.CreateStringItem(ContentType.Text, jsonoutput));
}
catch (Exception ex)
{
Logger.Error("Exception raised:" + ex.Message);
}
}
private Dictionary<string, object> GetXmlValues(XElement xml)
{
var attr = xml.Attributes().ToDictionary(d => d.Name.LocalName, d => (object)d.Value);
if (xml.HasElements) attr.Add("_value", xml.Elements().Select(e => GetXmlValues(e)));
else if (!xml.IsEmpty) attr.Add("_value", xml.Value);
return new Dictionary<string, object> { { xml.Name.LocalName, attr } };
}