gpt4 book ai didi

c# - 使用 XmlSerializer 忽略 .NET 中 Xml 序列化中的属性

转载 作者:太空狗 更新时间:2023-10-30 01:05:39 25 4
gpt4 key购买 nike

我正在使用 XmlSerializer 执行 Xml 序列化。我正在对 ClassA 进行序列化,其中包含 ClassB 类型的名为 MyProperty 的属性。我不想序列化 ClassB 的特定属性。

我必须使用 XmlAttributeOverrides,因为类在另一个库中。如果该属性本身位于 ClassA 中,那就很简单了。

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:

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());
}
}

主要方法:

void Main()
{
var classA = new ClassA {
MyProperty = new ClassB {
ThePropertyNameToIgnore = "Hello",
Prop2 = "World!"
}
};

Console.WriteLine(ToXml(classA));
}

输出省略了“ThePropertyNameToIgnore”:

<?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>

关于c# - 使用 XmlSerializer 忽略 .NET 中 Xml 序列化中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17947998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com