【发布时间】:2016-11-15 14:45:07
【问题描述】:
我正在尝试序列化一个 xml 文档,其中一个节点给我带来了麻烦。我的 xml 文档是:
<?xml version="1.0" encoding="utf-8"?>
<item id="tcm:38-21324" title="Accessibility Product Accessibility content - 11-INTL" type="Component">
<title>Accessibility Product Accessibility content - 11-INTL</title>
<generalContent xmlns="uuid:bc85180b-db18-412f-b7ad-36a25ff4012f">
<title>Produkttilgængelighed</title>
<style xlink:href="tcm:38-3149-1024" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:title="Horizontal Rule (Blue)">Horizontal Rule (Blue)</style>
<image>
<image xlink:type="simple" xlink:href="tcm:38-33683" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:title="Feature-Image_D_527478227_kp" />
<smallImage xlink:type="simple" xlink:href="tcm:38-33684" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:title="Feature-Image_M_527478227_kp" />
<retinaImage xlink:type="simple" xlink:href="tcm:38-33685" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:title="Feature-Image_T_527478227_kp" />
<altText>Kvinde med briller kigger på en bærbar computer</altText>
<title>Kvinde med briller kigger på en bærbar computer</title>
<imagePosition>Right</imagePosition>
</image>
<description>
<hr class="mainRow__hr mainRow__hr--bbOrange" xmlns="http://www.w3.org/1999/xhtml" />
<p xmlns="http://www.w3.org/1999/xhtml">Vores produkter er designet og udviklet</p>
</description>
</generalContent>
</item>
这是我的模型。它适用于除描述字段之外的其他字段。
[Serializable()]
[XmlRoot(ElementName = "generalContent", Namespace = "uuid:bc85180b-db18-412f-b7ad-36a25ff4012f")]
public class GeneralContent
{
[XmlElement(ElementName = "title")]
public string Title { get; set; }
[XmlElement(ElementName = "image")]
public Image Image { get; set; }
[XmlElement(ElementName = "description")]
public string Description { get; set; }
}
执行序列化的代码是通用代码,适用于我的所有其他模型。
public static T MapXmlToType<T>(XElement xmlData) where T:ITridionModel
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
return (T) xmlSerializer.Deserialize(xmlData.CreateReader());
}
我需要将“描述”节点作为字符串获取。它基本上是一个富文本字段,我需要包括样式值在内的全部内容。但是,这个模型现在为描述节点抛出System.InvalidOperationException。如何序列化?
【问题讨论】:
-
请发布您的代码序列化/反序列化代码。您是在尝试序列化(写入 XML)还是反序列化(读取 XML)?
-
我认为您需要手动实现描述属性的序列化,并禁用所有被解释为 xml 或特殊字符的 rtf 标签(请参阅 IXmlSerializable)
-
erm,XML 被序列化了。
-
可能你的富文本是html而不是rtf?
-
在我看来,您正在将标记代码与文本分开。但是描述属性不知道如何解码。如果您将标记与文本一起作为一个字符串保留,它应该可以正常工作。如有必要,您可以使用 RichTextBox。 rtf 属性会返回这样一个字符串。
标签: c# xml xmlserializer