忽略XML序列化属性的属性使用XmlSerializer的.NET [英] Ignore property of a property in Xml Serialization in .NET using XmlSerializer
问题描述
我进行使用XML serrialization 的XmlSerializer
。我进行序列化 ClassA的
,其中包含一个名为类型的 myProperty的
属性 ClassB的
。我不想要的特定财产 ClassB的
序列化。
I am carrying out Xml serrialization using XmlSerializer
. I am carrying out serialization of ClassA
, which contains property named MyProperty
of type ClassB
. I don't want a particular property of ClassB
to be serialized.
我必须使用 XmlAttributeOverrides
由于类是在另一个库。
如果属性是 ClassA的
本身,那将是直接的。
I have to use XmlAttributeOverrides
as the classes are in another library.
If the property was in ClassA
itself, it would have been straightforward.
XmlAttributeOverrides xmlOver = new XmlAttributeOverrides();
XmlAttributes xmlAttr = new XmlAttributes();
xmlAttr.XmlIgnore = true;
xmlOver.Add(typeof(ClassA), "MyProperty", xmlAttr);
XmlSerializer ser = new XmlSerializer(typeof(ClassA), xmlOver);
如何完成,如果该属性是在 ClassB的
,我们需要序列 ClassA的
?
推荐答案
您几乎得到了它,只是更新替代来指向 ClassB的
而不是 ClassA的
:
You almost got it, just update your overrides to point to ClassB
instead of 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);
快速测试,给出:
Quick test, given:
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());
}
}
主要方法:
void Main()
{
var classA = new ClassA {
MyProperty = new ClassB {
ThePropertyNameToIgnore = "Hello",
Prop2 = "World!"
}
};
Console.WriteLine(ToXml(classA));
}
输出这个与ThePropertyNameToIgnore省略:
Outputs this with "ThePropertyNameToIgnore" omitted:
<?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>
这篇关于忽略XML序列化属性的属性使用XmlSerializer的.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!