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?
-
I think the best way for me right now is to remove all the 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 instance from 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; }
0 comments:
Post a Comment