好吧,这个成功了!感谢大家!
public class Result
{
public String htmlEscaped
{
set;
get;
}
[XmlIgnore]
public String htmlValue
{ set; get; }
[XmlElement("htmlValue")]
public XmlCDataSection htmlValueCData
{
get
{
XmlDocument _dummyDoc = new XmlDocument();
return _dummyDoc.CreateCDataSection(htmlValue);
}
set { htmlValue = (value != null) ? value.Data : null; }
}
}
Result r = new Result();
r.htmlValue = ("<b>Hello</b>");
r.htmlEscaped = ("<b>Hello</b>");
XmlSerializer xml = new XmlSerializer(r.GetType());
TextWriter file = new StreamWriter(Environment.CurrentDirectory + "\\results\\result.xml", false, System.Text.Encoding.Default);
xml.Serialize(file, r);
file.Close();
结果:
<?xml version="1.0" encoding="Windows-1252"?>
<Result xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<htmlEscaped><b>Hello</b></htmlEscaped>
<htmlValue><![CDATA[<b>Hello</b>]]></htmlValue>
</Result>
如您所见,在 CDATA 为返回类型后,文件系统上的 XML 文件中不再有转义 html。JSON 序列化不再起作用,但这可以通过一点类型扩展来解决。
问题是:
也许有人知道如何做到这一点......
我有这个类:
public class Result
{
public String htmlValue
{
get;
set;
}
}
我用它来将它序列化为 XML
Result res = new Result();
res.htmlValue = "<p>Hello World</p>";
XmlSerializer s = new XmlSerializer(res.GetType());
TextWriter w = new StreamWriter(Environment.CurrentDirectory + "\\result.xml", false, System.Text.Encoding.Default);
s.Serialize(w, res);
w.Close();
工作正常我明白了:
<?xml version="1.0" encoding="Windows-1252"?>
<Result xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<htmlValue><b>Hello World</b></htmlValue>
</Result>
我可以做些什么改变才能得到这个:
<?xml version="1.0" encoding="Windows-1252"?>
<Result xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<htmlValue><![CDATA[<b>Hello World</b>]]></htmlValue>
</Result>
我已经搜索过了,但我找不到任何东西。htmlValue 的类型必须保持 String,因为其他序列化 JSON 等。
棘手的一个...提前感谢您的建议
- HTML 在 C# 中的 String 中是正确的。为什么要解码或编码?
- XmlSerializer 将转义的 HTML 保存为 XML 文件。
- 不要使用 C# 来消费。
是接受这个的外部工具:
<htmlValue><![CDATA[<b>Hello World</b>]]></htmlValue>
但不是
<htmlValue><b>Hello World</b></htmlValue>
我对 JSON Serializer 做同样的事情,在硬盘驱动器上的文件中,HTML 保存正确。为什么以及在哪里使用 HTTP 实用程序来防止这种情况?以及如何<![CDATA[ ]]>
绕过它。
能给个代码示例吗?除了 C# 自己的序列化器之外,还有其他序列化器吗?
我从 Marco André Silva 找到了这个 Link .NET XML Serialization of CDATA ATTRIBUTE,我需要这样做,但不同的是,如何在不更改类型的情况下包含它?