¿Cómo puedo acceder a XmlAttributes
aplicado a campos en un objeto IXmlSerializable
usando ?Acceder a atributos agregados XmlAttributesOverrides en métodos IXmlSerializable
la muestra objeto 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
}
}
}
}
típica creación de anulación:
// 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 ...
Creado salida:
<?xml version="1.0" encoding="utf-8"?><Person><Name1>First</Name1><Name2>Second</Name2></Person>
necesito utilizar IXmlSerializable
para superar los problemas de herencia de 'SomeBaseClass'.
El problema es que GetCustomArributes
no devuelve ninguno de los atributos agregados a la colección XmlAttributeOverrides
- ¡o lo estoy haciendo incorrectamente!
También es probable que GetCustomAttributes
no se SUPONE para devolver tales atributos adicionales, o que se supone que no debo usar XmlAttributeOverrides
en una clase IXmlSerializable
.
Entonces ... cualquier idea o alternativa. Gracias por tomarse el tiempo.
¿Hay alguna razón en particular, ¿por qué no se puede simplemente les inyecta a la clase Persona directa? Por ejemplo, haga el método SetOverrides (XmlAttributeOverrides overrides) en la clase Person y llámelo antes de que se serialice. –
@OndrejSvejdar Eso funcionará para la serialización pero NO para la deserialización. –