을 사용하여 IXmlSerializable
개체의 필드에 적용된 XmlAttributes
에 어떻게 액세스합니까?XmlAttributesOverrides에서 IXmlSerializable 메서드의 특성을 추가했습니다.
샘플 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
}
}
}
}
일반 재정의 생성 :
// 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 ...
만든 출력 :
<?xml version="1.0" encoding="utf-8"?><Person><Name1>First</Name1><Name2>Second</Name2></Person>
내가 'SomeBaseClass'에서 상속 문제를 극복하기 위해 IXmlSerializable
를 사용해야합니다.
문제는 GetCustomArributes
이 (가) XmlAttributeOverrides
컬렉션에 추가 된 속성을 반환하지 않거나 잘못하고 있다는 것입니다.
GetCustomAttributes
이 추가 된 특성을 반환하지 않거나 클래스에서 XmlAttributeOverrides
을 사용하지 않아도되는 것 같습니다.
그래서 ... 아이디어 나 대안. 시간을내어 주셔서 감사합니다.
어떤 특별한 이유가 그냥 직접 Person 클래스에 주입 할 수없는 이유 있나요? 예를 들어, Person 클래스에서 SetOverrides (XmlAttributeOverrides 오버라이드) 메소드를 만들고 직렬화되기 전에 바로 호출 할 수 있습니까? –
@OndrejSvejdar 직렬화에는 작동하지만 비 직렬화에는 작동하지 않습니다. –