【问题标题】:How to prevent object to be serialize in XML如何防止对象在 XML 中被序列化
【发布时间】:2014-12-06 09:56:53
【问题描述】:

IDE:VS、C# .net 4.0、winforms

在 XMLSerializer 的帮助下,我能够生成 C# 对象的 XML,但我想删除特定对象。

有什么方法可以防止特定对象在 XML 中被阻止..?

 using (MemoryStream xmlStream = new MemoryStream())
        {
            /* 
            XmlSerializer.Serialize Method (XmlWriter, Object)
            Serializes the specified Object and writes the XML document to a file using the specified xmlwriter 

            Parameters
            xmlWriter-

            Type: System.Xml.XmlWriter

            The XmlWriter used to write the XML document. 
            Type: System.Object
            The Object to serialize. 

             */

            xmlSerializer.Serialize(xmlStream, YourClassObject);
            xmlStream.Position = 0;

            //Loads the XML document from the specified string.
            xmlDoc.Load(xmlStream);

            string fileName = YourClassObject.GetType().Name;
            xmlDoc.Save("C:\\Users\\Yogesh\\Desktop\\Yardz_XMLS\\" + fileName + ".xml");
            return xmlDoc.InnerXml;  

有什么方法可以防止某些属性被序列化..?

【问题讨论】:

  • 防止序列化特定的对象属性?后者很容易。另一方面,前者取决于你的真正意思。

标签: c# xml winforms


【解决方案1】:

XmlIgnore 属性放在你不需要序列化的属性上:

public class YourClass
{
    public string Serailized { get; set; }

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

有关详细信息,请参阅“Controlling XML Serialization Using Attributes”。

【讨论】:

    猜你喜欢
    • 2023-03-28
    • 2010-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    • 2012-08-04
    相关资源
    最近更新 更多