Je réalise la sérialisation Xml en utilisant XmlSerializer
. Je réalise la sérialisation de ClassA
, qui contient la propriété nommée MyProperty
de type ClassB
. Je ne veux pas une propriété particulière de ClassB
être sérialisé.
Je dois utiliser XmlAttributeOverrides
comme les classes sont dans une autre bibliothèque. Si la propriété était en ClassA
elle-même, cela aurait été simple.
XmlAttributeOverrides xmlOver = new XmlAttributeOverrides();
XmlAttributes xmlAttr = new XmlAttributes();
xmlAttr.XmlIgnore = true;
xmlOver.Add(typeof(ClassA), "MyProperty", xmlAttr);
XmlSerializer ser = new XmlSerializer(typeof(ClassA), xmlOver);
Comment accomplir si la propriété est en ClassB
et nous devons sérialiser ClassA
?
Réponses:
4 pour la réponse № 1Vous l’avez presque eu, il suffit de mettre à jour vos remplacements pour pointer vers ClassB
au lieu de ClassA
:
XmlAttributeOverrides xmlOver = new XmlAttributeOverrides();
XmlAttributes xmlAttr = new XmlAttributes();
xmlAttr.XmlIgnore = true;
//change this to point to ClassB"s property to ignore
xmlOver.Add(typeof(ClassB), "ThePropertyNameToIgnore", xmlAttr);
XmlSerializer ser = new XmlSerializer(typeof(ClassA), xmlOver);
Test rapide, étant donné:
public class ClassA
{
public ClassB MyProperty { get; set; }
}
public class ClassB
{
public string ThePropertyNameToIgnore { get; set; }
public string Prop2 { get; set; }
}
Et méthode d'exportation:
public static string ToXml(object obj)
{
XmlAttributeOverrides xmlOver = new XmlAttributeOverrides();
XmlAttributes xmlAttr = new XmlAttributes();
xmlAttr.XmlIgnore = true;
xmlOver.Add(typeof(ClassB), "ThePropertyNameToIgnore", xmlAttr);
XmlSerializer xs = new XmlSerializer(typeof(ClassA), xmlOver);
using (MemoryStream stream = new MemoryStream())
{
xs.Serialize(stream, obj);
return System.Text.Encoding.UTF8.GetString(stream.ToArray());
}
}
Méthode principale:
void Main()
{
var classA = new ClassA {
MyProperty = new ClassB {
ThePropertyNameToIgnore = "Hello",
Prop2 = "World!"
}
};
Console.WriteLine(ToXml(classA));
}
Sort ceci avec "ThePropertyNameToIgnore" omis:
<?xml version="1.0"?>
<ClassA xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MyProperty>
<Prop2>World!</Prop2>
</MyProperty>
</ClassA>