(don't ?) use JavaScriptSerializer to convert xml file (of unknown schema) to json in c#

混江龙づ霸主 提交于 2019-12-24 00:44:13

问题


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());

回答1:


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"
//      }
//    ]
//  }
//}


来源:https://stackoverflow.com/questions/6760232/dont-use-javascriptserializer-to-convert-xml-file-of-unknown-schema-to-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!