好的,这个成功了!感谢你们所有人!
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 的类型 必须保留字符串,因为其他序列化 JSON 等。
棘手的...提前感谢您的建议
- HTML 在 C# 中的字符串中是正确的。为什么要解码或编码?
- XmlSerializer 将转义后的 HTML 保存为 XML 文件。
- 不要使用 C# 进行消费。
是接受这个的外部工具:
<htmlValue><![CDATA[<b>Hello World</b>]]></htmlValue>
但不是
<htmlValue><b>Hello World</b></htmlValue>
我对 JSON Serializer 做同样的事情,在硬盘驱动器上的文件中,HTML 被正确保存。
为什么以及在哪里使用 HTTP Utility 来防止这种情况发生?以及如何获得<![CDATA[ ]]>
围绕着它。
你能给个代码示例吗? 除了 C# 自带的序列化程序之外,还有其他序列化程序吗?
我找到了这个链接 .NET XML Serialization of CDATA ATTRIBUTE 来自 Marco André Silva,我需要做什么,但不同的是,如何在不更改类型的情况下包含它?
最佳答案
这里有一个简单的技巧来实现您想要的效果。您只需要序列化 XmlCDataSection 属性而不是字符串属性:
(和John的建议差不多,只是简单了一点……)
public class Result
{
[XmlIgnore]
public String htmlValue
{
get;
set;
}
private static XmlDocument _dummyDoc;
[XmlElement("htmlValue")]
public XmlCDataSection htmlValueCData
{
get { return _dummyDoc.CreateCDataSection(htmlValue); }
set { htmlValue = (value != null) ? value.Data : null; }
}
}
关于c# - HTML 的 XML 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1506499/