【问题标题】:Serialise empty strings as nulls so they are not output将空字符串序列化为空值,因此它们不会被输出
【发布时间】:2017-06-07 07:23:33
【问题描述】:

我有一个由第三方提供的 XSD,然后我使用 xsd.exe 将其转换为类。

由于我们不拥有此 XSD,我试图不以任何方式更改生成的类。

无需对我们正在映射的每个字段手动应用空白字符串检查,例如:

!String.IsNullOrWhiteSpace(field) ? field : null;

我想不出一种简单的方法来序列化空白字符串,这意味着它们根本不输出(不产生标签)。

我们无法输出空白字符串的原因是因为 XSD 具有模式约束,例如 StringM50m1,我认为这意味着需要最小长度 1(但是,如果没有内容,他们很乐意不接收标签)输出后验证失败,并显示以下消息:

'field' 元素无效 - 根据其数据类型 '' 的值无效 'StringM50m1' - 模式约束失败。

任何想法都将不胜感激。

【问题讨论】:

标签: c# xml serialization


【解决方案1】:

如果您使用 XmlSerializer,您可以为所需属性添加 XmlDefaultValue:

private static void Serialize()
{
    XsdClass xc = new XsdClass();
    xc.SomeString1 = string.Empty;
    xc.SomeString2 = "value";
    xc.SomeString3 = null;

    XmlAttributeOverrides overrides = new XmlAttributeOverrides();
    XmlAttributes attribs = new XmlAttributes();
    attribs.XmlDefaultValue = string.Empty;
    foreach (var prop in TypeDescriptor.GetProperties(typeof(XsdClass)).Cast<PropertyDescriptor>().Where(x => !x.IsReadOnly && x.PropertyType == typeof(string)))
        overrides.Add(typeof(XsdClass), prop.Name, attribs);

    XmlSerializer serializer = new XmlSerializer(typeof(XsdClass), overrides);
    string result;
    using (StringWriter textWriter = new StringWriter())
    {
        serializer.Serialize(textWriter, xc);
        result = textWriter.ToString();
    }
}

public class XsdClass 
{
    public string SomeString1 { get; set; }
    public string SomeString2 { get; set; }
    public string SomeString3 { get; set; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多