Comment puis-je accéder aux champs XmlAttributes
d'un objet IXmlSerializable
en utilisant XmlAttributesOverrides
?Accès aux attributs XmlAttributesOverrides ajoutés dans les méthodes IXmlSerializable
échantillon objet IXmlSerializable:
public class Person : SomeBaseClass, IXmlSerializable
{
public string Name1;
public string Name2;
[XmlIgnore]
public string Name3;
public Person()
{
}
public Person(string first, string second, string third)
{
Name1 = first;
Name2 = second;
Name3 = third;
}
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
// ....
}
public void WriteXml(XmlWriter writer)
{
FieldInfo[] finfo = this.GetType().GetFields();
foreach (FieldInfo finf in finfo)
{
FieldAttributes attr = finf.Attributes;
object[] atts = finf.GetCustomAttributes(true);
if (atts.Length == 0)
{
// handle field with no attributes ... should be just Name1
// but also get Name2 since XmlAttributOverrides' XmlIgnore is not
// included with GetCustomAttributes results.
writer.WriteElementString(finf.Name, (string)finf.GetValue(this));
}
else
{
// handle field with attributes ... should be Name2 and Name3
// but only get Name3 via [XmlIgnore] compiler generated attribute
}
}
}
}
création Override typique:
// parent app ...
public XmlSerializer CreateOverrider()
{
XmlAttributeOverrides xOver = new XmlAttributeOverrides();
XmlAttributes attrs = new XmlAttributes();
attrs.XmlIgnore = true;
xOver.Add(typeof(Person), "name2", attrs);
XmlSerializer xSer = new XmlSerializer(typeof(Person), xOver);
return xSer;
}
private void button2_Click(object sender, EventArgs e)
{
// Custom XmlSerialize
Person pson = new Person("First", "Second", "Third");
XmlSerializer serializer = CreateOverrider();
TextWriter writer = new StreamWriter("PersonOverride.xml");
serializer.Serialize(writer, pson);
writer.Close();
}
// etc ...
Créé Sortie:
<?xml version="1.0" encoding="utf-8"?><Person><Name1>First</Name1><Name2>Second</Name2></Person>
Je dois utiliser IXmlSerializable
pour surmonter les problèmes d'héritage de 'SomeBaseClass'. Le problème est que GetCustomArributes
ne retourne aucun des attributs ajoutés à la collection XmlAttributeOverrides
- ou je le fais mal!?
Il est également probable que GetCustomAttributes
n'est pas SUPPOSÉ pour renvoyer de tels attributs ajoutés, ou que je ne suis pas censé utiliser XmlAttributeOverrides
dans une classe IXmlSerializable
.
Alors ... des idées ou des alternatives. Merci d'avoir pris le temps.
est-il une raison particulière, pourquoi vous ne pouvez pas les injecter directement à la classe personne? Par exemple rendre la méthode SetOverrides (XmlAttributeOverrides overrides) sur la classe Person et l'appeler juste avant qu'il ne soit sérialisé? –
@OndrejSvejdar Cela fonctionnera pour la sérialisation mais PAS pour la désérialisation. –