本文介绍了如何为CDATA使用XmlSerializer的序列化字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能通过某种属性为CDATA使用.net XmlSerializer的序列化字符串?

解决方案

  [XmlRoot(根)
公共类Sample1Xml
{
    内部Sample1Xml()
    {
    }

    [的XmlElement(节点)
    公众的NodeType节点{获得;组; }

    #地区的嵌套式:的NodeType

    公共类的NodeType
    {
        [XmlAttribute(attR1位)]
        公共字符串ATTR1 {获得;组; }

        [XmlAttribute(attR2位)]
        公共字符串attR2位{获得;组; }

        [XmlIgnore]
        公共字符串内容{获得;组; }

        [XMLTEXT]
        公众的XmlNode [] CDataContent
        {
            得到
            {
                VAR哑=新的XmlDocument();
                返回新的XmlNode [] {dummy.CreateCDataSection(内容)};
            }
            组
            {
                如果(价值== NULL)
                {
                    内容= NULL;
                    返回;
                }

                如果(value.Length!= 1)
                {
                    抛出新的InvalidOperationException异常(
                        的String.Format(
                            无效的数组长度{0},value.Length));
                }

                内容=值[0] .value的;
            }
        }
    }

    #endregion
}
 

Is it possible via an attribute of some sort to serialize a string as CDATA using the .Net XmlSerializer?

解决方案
[XmlRoot("root")]
public class Sample1Xml
{
    internal Sample1Xml()
    {
    }

    [XmlElement("node")]
    public NodeType Node { get; set; }

    #region Nested type: NodeType

    public class NodeType
    {
        [XmlAttribute("attr1")]
        public string Attr1 { get; set; }

        [XmlAttribute("attr2")]
        public string Attr2 { get; set; }

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

        [XmlText]
        public XmlNode[] CDataContent
        {
            get
            {
                var dummy = new XmlDocument();
                return new XmlNode[] {dummy.CreateCDataSection(Content)};
            }
            set
            {
                if (value == null)
                {
                    Content = null;
                    return;
                }

                if (value.Length != 1)
                {
                    throw new InvalidOperationException(
                        String.Format(
                            "Invalid array length {0}", value.Length));
                }

                Content = value[0].Value;
            }
        }
    }

    #endregion
}

这篇关于如何为CDATA使用XmlSerializer的序列化字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 01:08