Przeprowadzam serializację Xml przy użyciu XmlSerializer
. Przeprowadzam serializację ClassA
, który zawiera właściwość o nazwie MyProperty
typu ClassB
. Nie chcę określonej własności ClassB
do serializacji.
Muszę użyć XmlAttributeOverrides
ponieważ klasy znajdują się w innej bibliotece. Jeśli nieruchomość była w ClassA
samo byłoby proste.
XmlAttributeOverrides xmlOver = new XmlAttributeOverrides();
XmlAttributes xmlAttr = new XmlAttributes();
xmlAttr.XmlIgnore = true;
xmlOver.Add(typeof(ClassA), "MyProperty", xmlAttr);
XmlSerializer ser = new XmlSerializer(typeof(ClassA), xmlOver);
Jak to zrobić, jeśli właściwość jest w ClassB
i musimy dokonać serializacji ClassA
?
Odpowiedzi:
4 dla odpowiedzi № 1Prawie to masz, po prostu zaktualizuj swoje przesłonięcia, aby wskazywały ClassB
zamiast 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);
Szybki test, biorąc pod uwagę:
public class ClassA
{
public ClassB MyProperty { get; set; }
}
public class ClassB
{
public string ThePropertyNameToIgnore { get; set; }
public string Prop2 { get; set; }
}
I metoda eksportu:
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());
}
}
Główna metoda:
void Main()
{
var classA = new ClassA {
MyProperty = new ClassB {
ThePropertyNameToIgnore = "Hello",
Prop2 = "World!"
}
};
Console.WriteLine(ToXml(classA));
}
Wyprowadza to z pominięciem „ThePropertyNameToIgnore”:
<?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>