1

我有以下功能:

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 中有任何选项可以在反序列化为对象时忽略注释?

4

1 回答 1

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 字符串中获取实例的函数:

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;
}
于 2009-05-11T03:51:18.823 回答