Reputation: 1597
Is JavascriptSerializer the "tool" to convert an xml file (of unknown schema) into a json string ?
There are some threads here dealing about how to convert xml to json in c#. And some recommended dedicated solutions (http://www.phdcc.com/xml2json.htm)
But in those threads there are always one suggesting using JavaScriptSerializer. But there is never clear explanation on how to do it. One always elude it or start with an object instead of an xml.
To make it clear : I don't look after having my xml turned into objects. If I can, I'd prefer to avoid it. XML => Json would please me more than XML => objects => Json.
But everybody is telling don't reinvent wheel use JavaScriptSerializer. But I don't feel like this is the way to go. Setting up objects from xml looks like a terrible task (strongly typing).
So my question is :
Should I stay with the quick (but "dirty") methods described in http://www.phdcc.com/xml2json.htm
Or
Could I use JavascriptSerializer even if I don't know the schema of the xml ? If so please fill in the gaps/modify the following code
namespace ExtensionMethods {
public static class JSONHelper
{
public static string ToJSON(this XmlDocument doc)
{
object obj = get_An_Object_From_My_XML_Without_Too_Much_Hassle_Like_Having_To_Deal_With_Strongly_Type(doc); // how to do that ???
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}
}
}
using ExtensionMethods;
...
XmlDocument mydoc = new XmlDocument(@"c:\test.xml");
Response.write(mydoc.ToJSON());
Upvotes: 2
Views: 2685
Reputation: 5747
I think you could use json.net in order to receive a unknown xml into a json object:
string xml = @"<?xml version=""1.0"" standalone=""no""?>
<root>
<person id=""1"">
<name>Alan</name>
<url>http://www.google.com</url>
</person>
<person id=""2"">
<name>Louis</name>
<url>http://www.yahoo.com</url>
</person>
</root>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);
//{
// "?xml": {
// "@version": "1.0",
// "@standalone": "no"
// },
// "root": {
// "person": [
// {
// "@id": "1",
// "name": "Alan",
// "url": "http://www.google.com"
// },
// {
// "@id": "2",
// "name": "Louis",
// "url": "http://www.yahoo.com"
// }
// ]
// }
//}
Upvotes: 1