序列化/反序列化问题包含CDATA属性的XML

时间:2011-03-19 19:21:48

标签: c# .net xml xml-serialization cdata

我需要反序列化/序列化下面的xml文件:

<items att1="val">
<item att1="image1.jpg">
         <![CDATA[<strong>Image 1</strong>]]>
</item>
<item att1="image2.jpg">
         <![CDATA[<strong>Image 2</strong>]]>
</item>     
</items>

我的C#课程:

[Serializable]
[XmlRoot("items")]    
public class RootClass
{
  [XmlAttribute("att1")]
  public string Att1 {set; get;}

  [XmlElement("item")]  
  public Item[] ArrayOfItem {get; set;}
}

  [Serializable]
public class Item
{
    [XmlAttribute("att1")]
    public string Att1 { get; set; }

    [XmlText]
    public string Content { get; set; }
}

并且所有工作都近乎完美但在反序列化之后

<![CDATA[<strong>Image 1</strong>]]>

我有

&lt;strong&gt;Image 1&lt;/strong&gt;

我试图将XmlCDataSection用作Content属性的类型,但XmlText属性不允许使用此类型。不幸的是我无法改变XML结构。

我该如何解决这个问题?

4 个答案:

答案 0 :(得分:1)

这应该有帮助

    private string content;

    [XmlText]
    public string Content
    {
        get { return content; }
        set { content = XElement.Parse(value).Value; }
    }

答案 1 :(得分:1)

答案 2 :(得分:1)

首先将属性声明为XmlCDataSection

public XmlCDataSection ProjectXml { get; set; }

在这种情况下,projectXml是一个字符串xml

ProjectXml = new XmlDocument().CreateCDataSection(projectXml);

当你序列化你的消息时,你会得到你很好的格式(通知)

<?xml version="1.0" encoding="utf-16"?>
<MessageBase xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:type="Message_ProjectStatusChanged">
  <ID>131</ID>
  <HandlerName>Plugin</HandlerName>
  <NumRetries>0</NumRetries>
  <TriggerXml><![CDATA[<?xml version="1.0" encoding="utf-8"?><TmData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Version="9.0.0" Date="2012-01-31T15:46:02.6003105" Format="1" AppVersion="10.2.0" Culture="en-US" UserID="0" UserRole=""><PROJECT></PROJECT></TmData>]]></TriggerXml>
  <MessageCreatedDate>2012-01-31T20:28:52.4843092Z</MessageCreatedDate>
  <MessageStatus>0</MessageStatus>
  <ProjectId>0</ProjectId>
  <UserGUID>8CDF581E44F54E8BAD60A4FAA8418070</UserGUID>
  <ProjectGUID>5E82456F42DC46DEBA07F114F647E969</ProjectGUID>
  <PriorStatus>0</PriorStatus>
  <NewStatus>3</NewStatus>
  <ActionDate>0001-01-01T00:00:00</ActionDate>
</MessageBase>

答案 3 :(得分:0)

StackOverflow中提供的大多数解决方案仅适用于序列化,而不适用于反序列化。这个将完成这项工作,如果您需要从代码中获取/设置值,请使用我添加的额外属性PriceUrlByString。

    private XmlNode _priceUrl;
    [XmlElement("price_url")]
    public XmlNode PriceUrl
    {
        get
        {
            return _priceUrl;
        }
        set
        {
            _priceUrl = value;
        }
    }

    [XmlIgnore]
    public string PriceUrlByString
    {
        get
        {
            // Retrieves the content of the encapsulated CDATA
            return _priceUrl.Value;
        }

        set
        {
            // Encapsulate in a CDATA XmlNode
            XmlDocument xmlDocument = new XmlDocument();
            this._priceUrl = xmlDocument.CreateCDataSection(value);
        }
    }
相关问题