JSON.Net: Convert JSON string from XML string to instance

I have the following function:

public static T GetInstance<T>(string xmlString)
{
   var xmlDoc = new XmlDocument();
   xmlDoc.Load(new StringReader(xmlString));
   string jsonString = JsonConvert.SerializeXmlNode(xmlDoc.DocumentElement);
   T instance = JsonConvert.DeserializeObject(jsonString, typeof(T)) as T;
   return instance;
}

      

It works great for regular XML strings. However, if the input XML string contains comments such as:

....
<!-- some comments ... 
-->
....

      

Then calling the JsonConvert.DeserializeObject () function will throw an exception:

Newtonsoft.Json.JsonSerializationException was unhandled
Message="Unexpected token when deserializing object: Comment"
Source="Newtonsoft.Json"
StackTrace:
   at Newtonsoft.Json.JsonSerializer.PopulateObject(Object newObject, JsonReader reader, Type objectType)
   ....

      

Either I need to truncate all comments in the XML line, or I can use any options in JsonConvert to ignore comments.

For the first option, if I need to remove all comments with an XmlDocument, are there any options in the XmlDocument available to convert an XML string to XML string only for nodes?

For the second option, I prefer if there is any option in Json.Net to ignore comments when de-saling an object?

+1


a source to share


1 answer


I think the best way for me now is to remove all comment nodes from the xml string first.

public static string RemoveComments(
        string xmlString,
        int indention)
{
   XmlDocument xDoc = new XmlDocument();
   xDoc.PreserveWhitespace = false;
   xDoc.LoadXml(xmlString);
   XmlNodeList list = xDoc.SelectNodes("//comment()");

   foreach (XmlNode node in list)
   {
      node.ParentNode.RemoveChild(node);
   }

   string xml;
   using (StringWriter sw = new StringWriter())
   {
      using (XmlTextWriter xtw = new XmlTextWriter(sw))
      {
        if (indention > 0)
        {
          xtw.IndentChar = ' ';
          xtw.Indentation = indention;
          xtw.Formatting = System.Xml.Formatting.Indented;
        }

        xDoc.WriteContentTo(xtw);
        xtw.Close();
        sw.Close();
      }
      xml = sw.ToString();
    }

  return xml;
  }

      



And this is my function to get an instance from the xml string:

public static T GetInstance<T>(string xmlString)
{
  srring xml = RemoveComments(xmlString);
  var xmlDoc = new XmlDocument();
  xmlDoc.Load(new StringReader(xml));
  string jsonString = JsonConvert.SerializeXmlNode(xmlDoc.DocumentElement);
  T instance = JsonConvert.DeserializeObject(jsonString, typeof(T)) as T;
  return instance;
}

      

+3


a source







All Articles