[英]Custom XML Serialization and handling CDATA
I have a custom XML Serializer as follows 我有一个自定义XML序列化器,如下所示
public void WriteXml(XmlWriter writer)
{
foreach (PropertyInfo pi in this.GetType().GetProperties())
{
if (pi.GetCustomAttributes(typeof(XmlIgnoreAttribute), true).Count() == 0)
{
var attrList = pi.GetCustomAttributes(typeof(XmlElementAttribute), true);
if (attrList.Count() > 0)
{
XmlElementAttribute xe = (XmlElementAttribute)attrList[0];
writer.WriteStartElement(xe.ElementName);
}
else
{
writer.WriteStartElement(pi.Name);
}
if (pi.PropertyType == typeof(int) || (pi.PropertyType == typeof(float)))
{
writer.WriteString(pi.GetValue(this, null).ToString());
}
else if (pi.PropertyType == typeof(DateTime))
{
DateTime dt = (DateTime)(pi.GetValue(this, null));
writer.WriteString(dt.ToString("yyyyMMddHHmm"));
}
else
{
if (pi.GetValue(this, null) == null) writer.WriteString(String.Empty);
else
{
// write code to generate CDATA
String val = pi.GetValue(this, null).ToString();
if (val.IndexOfAny(invalidChars) != -1)
writer.WriteString(String.Format(@"<![CDATA[{0}]]>", pi.GetValue(this, null).ToString()));
else writer.WriteString(pi.GetValue(this, null).ToString());
}
}
writer.WriteEndElement();
}
}
}
}
} }
The problem arises when the value contains one of the characters which is invalid in an XML Value. 当值包含XML值中无效的字符之一时,就会出现问题。 This is detected successfully with these lines
这些行已成功检测到
if (val.IndexOfAny(invalidChars) != -1)
writer.WriteString(String.Format(@"<![CDATA[{0}]]>", pi.GetValue(this, null).ToString()));
else writer.WriteString(pi.GetValue(this, null).ToString());
The problem is the creation of the CDATA - instead of getting a properly formatted CDATA what I am getting is & gt ; 问题是CDATA的创建-而不是获取格式正确的CDATA,这是我所得到的&gt; and & lt ;
和&lt;
So how should you create a properly formatted CDATA within a custom serializer? 那么,如何在自定义序列化程序中创建格式正确的CDATA?
Answer provided by Jeroen Mostert in the comments. Jeroen Mostert在评论中提供了答案。
Replace the following code 替换以下代码
if (val.IndexOfAny(invalidChars) != -1) writer.WriteString(String.Format(@"<![CDATA[{0}]]>", pi.GetValue(this, null).ToString()));
else writer.WriteString(pi.GetValue(this, null).ToString());
with 与
if (val.IndexOfAny(invalidChars) != -1) writer.WriteRaw(String.Format(@"<![CDATA[{0}]]>", pi.GetValue(this, null).ToString()));
else writer.WriteString(pi.GetValue(this, null).ToString());
The CDATA is then written to the stream correctly and saved to disk in the correct format. 然后将CDATA正确写入流,并以正确格式保存到磁盘。
WriteString has been replaced with WriteRaw. WriteString已替换为WriteRaw。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.