我有以下功能:
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;
}
它适用于普通的XML字符串。但是,如果输入XML字符串包含注释,例如:
....
<!-- some comments ...
-->
....
然后对JsonConvert.DeserializeObject()的函数调用将抛出异常:
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)
....
要么我必须删除XML字符串中的所有注释,要么我可以使用JsonConvert中的任何选项设置来忽略注释。
对于第一个选项,如果我必须使用XmlDocument取出所有注释,XmlDocument中是否有可用于将XML字符串转换为仅节点XML字符串的选项?
对于第二个选项,我更喜欢,如果Json.Net中有任何选项在desialize to object时忽略注释?
答案 0 :(得分:3)
我认为现在最好的方法是首先从xml字符串中删除所有注释节点。
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;
}
这是我从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;
}