당신은 거의 그것을 가지고, 단지 ClassB
대신 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);
빠른 테스트를 :
public class ClassA
{
public ClassB MyProperty { get; set; }
}
public class ClassB
{
public string ThePropertyNameToIgnore { get; set; }
public string Prop2 { get; set; }
}
및 내보내기 방법 :
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());
}
}
Main 메서드 "ThePropertyNameToIgnore"와
void Main()
{
var classA = new ClassA {
MyProperty = new ClassB {
ThePropertyNameToIgnore = "Hello",
Prop2 = "World!"
}
};
Console.WriteLine(ToXml(classA));
}
출력이 생략 :
<?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>
나는 항상 다른 경우에 대한 ClassB''에서 속성을 무시하지 않으 받아? 그렇지 않으면'[XmlIgnore]'로'ClassBy.PropertyToIgnore'를 꾸미는 것만 큼 간단합니까? –
예 @ChrisSinclair, 맞습니다. – Brij