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 fine for normal XML strings. However, if the input XML string contains comments such as :
....
<!-- some comments ...
-->
....
Then the function call to JsonConvert.DeserializeObject() 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 have to trim out all the comments in the XML string, or if I can use any option settings in JsonConvert to ignore comments.
For the first option, if I have to take all the comments out by using XmlDocument, is there any options in XmlDocument available to convert an XML string to nodes-only XML string?
For the second option, I prefer, if there is any option in Json.Net to ignore comments when desialize to object?