如何防止对象在 XML 中序列化

本文关键字:序列化 XML 何防止 对象 | 更新日期: 2023-09-27 18:33:16

>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;  

有没有办法防止某些属性被序列化..?

如何防止对象在 XML 中序列化

XmlIgnore属性放在您不知道要序列化的属性上:

public class YourClass
{
    public string Serailized { get; set; }
    [XmlIgnore]
    public string NotSerialized { get; set; }
}

有关详细信息,请参阅"使用属性控制 XML 序列化"。

相关文章: