gpt4 book ai didi

c# - 如何让 XmlSerializer 忽略某种类型的所有成员?

转载 作者:行者123 更新时间:2023-11-30 17:34:28 25 4
gpt4 key购买 nike

我想将 XML 反序列化为以下类:

public partial class Delivery
{
public System.Nullable<System.DateTime> sentDate { get; set; }
public System.Nullable<System.DateTime> receivedDate { get; set; }
public System.Nullable<System.DateTime> responseDueDate { get; set; }
}

但是,XML 中的日期不是 XmlSerializer 友好格式。基于对多个问题的回答,我添加了这个类:

public partial class DateSafeDelivery : Delivery
{
[XmlElement("sentDate")]
public string sentDateString
{
internal get { return sentDate.HasValue ? XmlConvert.ToString(sentDate.Value) : null; }
set { sentDate = DateTime.Parse(value); }
}
[XmlElement("receivedDate")]
public string receivedDateString
{
internal get { return receivedDate.HasValue ? XmlConvert.ToString(receivedDate.Value) : null; }
set { receivedDate = DateTime.Parse(value); }
}
[XmlElement("responseDueDate")]
public string responseDueDateString
{
internal get { return responseDueDate.HasValue ? XmlConvert.ToString(responseDueDate.Value) : null; }
set { responseDueDate = DateTime.Parse(value); }
}
}

然后我配置我的覆盖:

private static XmlAttributeOverrides GetOverrides()
{
var overrides = new XmlAttributeOverrides();
var attributes = new XmlAttributes();
attributes.XmlElements.Add(new XmlElementAttribute(typeof(DateSafeDelivery)));
overrides.Add(typeof(MyParent), "Delivery", attributes);
var ignore = new XmlAttributes { XmlIgnore = true };
overrides.Add(typeof(DateTime?), ignore);
return overrides;
}

这导致以下预期:

Message=The string '2010-06-12T00:00:00 -05:00' is not a valid AllXsd value.
Source=System.Xml.ReaderWriter
StackTrace:
at System.Xml.Schema.XsdDateTime..ctor(String text, XsdDateTimeFlags kinds)
at System.Xml.XmlConvert.ToDateTime(String s, XmlDateTimeSerializationMode dateTimeOption)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderDeserializedAudit.Read1_NullableOfDateTime(Boolean checkType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderDeserializedAudit.Read15_DateSafeDelivery(Boolean isNullable, Boolean checkType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderDeserializedAudit.Read16_MyParent(Boolean isNullable, Boolean checkType)

所以 DateSafeDelivery 被使用了,但是日期的 XmlIgnore 被忽略了。

它会工作,如果我切换:

    overrides.Add(typeof(DateTime?), ignore);

与:

    new Dictionary<string, Type>()
{
{ "sentDate", typeof(Delivery) },
{ "receivedDate", typeof(Delivery) },
{ "responseDueDate", typeof(Delivery) },
}
.ToList()
.ForEach(t1 => overrides.Add(t1.Value, t1.Key, ignore));

这对于一个类和三个属性来说很好。但是我有 14 个类,总共有三打日期属性。我知道我必须为 14 个类添加覆盖,但是有没有办法让序列化程序忽略所有 DateTime 属性?

我以为XmlAttributeOverrides.Add Method (Type, XmlAttributes)会做的。但它不起作用。为什么?这个方法是做什么用的?它有什么作用?

最佳答案

XmlAttributeOverrides.Add(Type, XmlAttributes)旨在将 XML 覆盖属性添加到类型本身,而不是添加到返回该类型值的所有属性。例如。如果你想添加 [XmlRoot("OverrideName")]属性到 DateSafeDelivery,你可以这样做:

overrides.Add(typeof(DateSafeDelivery),
new XmlAttributes { XmlRoot = new XmlRootAttribute("OverrideName") });

没有动态覆盖属性来忽略返回给定类型的所有属性,因为没有 static XML serialization attribute可以抑制给定类型的所有属性的序列化。以下甚至无法编译,因为 [XmlIgnore]只能应用于属性或字段:

[XmlIgnore] public class IgnoreAllInstancesOfMe { } // Fails to compile.

(至于为什么 Microsoft 没有实现对应用于类型的 [XmlIgnore] 的支持 - 你需要问他们。)

因此您需要引入如下扩展方法:

public static partial class XmlAttributeOverridesExtensions
{
public static XmlAttributeOverrides IgnorePropertiesOfType(this XmlAttributeOverrides overrides, Type declaringType, Type propertyType)
{
return overrides.IgnorePropertiesOfType(declaringType, propertyType, new HashSet<Type>());
}

public static XmlAttributeOverrides IgnorePropertiesOfType(this XmlAttributeOverrides overrides, Type declaringType, Type propertyType, HashSet<Type> completedTypes)
{
if (overrides == null || declaringType == null || propertyType == null || completedTypes == null)
throw new ArgumentNullException();
XmlAttributes attributes = null;
for (; declaringType != null && declaringType != typeof(object); declaringType = declaringType.BaseType)
{
// Avoid duplicate overrides.
if (!completedTypes.Add(declaringType))
break;
foreach (var property in declaringType.GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance))
{
if (property.PropertyType == propertyType || Nullable.GetUnderlyingType(property.PropertyType) == propertyType)
{
attributes = attributes ?? new XmlAttributes { XmlIgnore = true };
overrides.Add(declaringType, property.Name, attributes);
}
}
}
return overrides;
}
}

然后做:

    private static XmlAttributeOverrides GetOverrides()
{
var overrides = new XmlAttributeOverrides();

var attributes = new XmlAttributes();
attributes.XmlElements.Add(new XmlElementAttribute(typeof(DateSafeDelivery)));
overrides.Add(typeof(MyParent), "Delivery", attributes);

// Ignore all DateTime properties in DateSafeDelivery
var completed = new HashSet<Type>();
overrides.IgnorePropertiesOfType(typeof(DateSafeDelivery), typeof(DateTime), completed);
// Add the other 14 types as required

return overrides;
}

另请注意,DateSafeDelivery 上的DateString 属性必须具有公共(public) get 和set 方法,例如:

public partial class DateSafeDelivery : Delivery
{
[XmlElement("sentDate")]
public string sentDateString
{
get { return sentDate.HasValue ? XmlConvert.ToString(sentDate.Value, XmlDateTimeSerializationMode.Utc) : null; }
set { sentDate = DateTime.Parse(value); }
}

XmlSerializer 无法序列化不完全公开的属性。

顺便说一句,请注意您必须静态缓存任何使用覆盖构造的 XmlSerializer 以避免严重的内存泄漏,如 this answer 中所述。 .

关于c# - 如何让 XmlSerializer 忽略某种类型的所有成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42376668/

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