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

时间:2014-12-06 09:56:54

标签: c# xml winforms

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;  

有没有办法阻止某些属性序列化??

1 个答案:

答案 0 :(得分:0)

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

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

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

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