81

我从第 3 方获得了一个 xml,我需要将其反序列化为 C# 对象。此 xml 可能包含值为整数类型或空值的属性:attr=”11” 或 attr=””。我想将此属性值反序列化为可空整数类型的属性。但 XmlSerializer 不支持反序列化为可空类型。以下测试代码在创建 XmlSerializer 期间失败,并出现 InvalidOperationException {“反映类型‘TestConsoleApplication.SerializeMe’的错误。”}。

[XmlRoot("root")]
public class SerializeMe
{
    [XmlElement("element")]
    public Element Element { get; set; }
}

public class Element
{
    [XmlAttribute("attr")]
    public int? Value { get; set; }
}

class Program {
    static void Main(string[] args) {
        string xml = "<root><element attr=''>valE</element></root>";
        var deserializer = new XmlSerializer(typeof(SerializeMe));
        Stream xmlStream = new MemoryStream(Encoding.ASCII.GetBytes(xml));
        var result = (SerializeMe)deserializer.Deserialize(xmlStream);
    }
}

当我将“Value”属性的类型更改为 int 时,反序列化失败并出现 InvalidOperationException:

XML 文档 (1, 16) 中存在错误。

任何人都可以建议如何将具有空值的属性反序列化为可空类型(作为空),同时将非空属性值反序列化为整数?这有什么技巧,所以我不必手动对每个字段进行反序列化(实际上有很多)?

ahsteele 发表评论后更新:

  1. Xsi:nil 属性

    据我所知,此属性仅适用于 XmlElementAttribute - 此属性指定元素没有内容,无论是子元素还是正文。但我需要找到 XmlAttributeAttribute 的解决方案。无论如何,我无法更改 xml,因为我无法控制它。

  2. bool *指定属性

    此属性仅在属性值非空或缺少属性时有效。当 attr 具有空值 (attr='') 时,XmlSerializer 构造函数将失败(如预期的那样)。

    public class Element
    {
        [XmlAttribute("attr")]
        public int Value { get; set; }
    
        [XmlIgnore]
        public bool ValueSpecified;
    }
    
  3. 自定义 Nullable 类,如 Alex Scordellis 的这篇博客文章

    我尝试将这篇博客文章中的课程用于我的问题:

    [XmlAttribute("attr")]
    public NullableInt Value { get; set; } 
    

    但 XmlSerializer 构造函数因 InvalidOperationException 而失败:

    无法序列化 TestConsoleApplication.NullableInt 类型的成员“值”。

    XmlAttribute/XmlText 不能用于编码实现 IXmlSerializable 的类型}

  4. 丑陋的替代解决方案(我很惭愧我在这里写了这段代码:)):

    public class Element
    {
        [XmlAttribute("attr")]
        public string SetValue { get; set; }
    
        public int? GetValue()
        {
            if ( string.IsNullOrEmpty(SetValue) || SetValue.Trim().Length <= 0 )
                return null;
    
            int result;
            if (int.TryParse(SetValue, out result))
                return result;
    
            return null;
        }
    }
    

    但我不想想出这样的解决方案,因为它破坏了我的类对其消费者的接口。我最好手动实现 IXmlSerializable 接口。

目前看来我必须为整个 Element 类(它很大)实现 IXmlSerializable 并且没有简单的解决方法......</p>

4

5 回答 5

69

这应该有效:

[XmlIgnore]
public int? Age { get; set; }

[XmlElement("Age")]
public string AgeAsText
{
  get { return (Age.HasValue) ? Age.ToString() : null; } 
  set { Age = !string.IsNullOrEmpty(value) ? int.Parse(value) : default(int?); }
}
于 2009-09-25T19:36:51.693 回答
23

我通过实现 IXmlSerializable 接口解决了这个问题。我没有找到更简单的方法。

这是测试代码示例:

[XmlRoot("root")]
public class DeserializeMe {
    [XmlArray("elements"), XmlArrayItem("element")]
    public List<Element> Element { get; set; }
}

public class Element : IXmlSerializable {
    public int? Value1 { get; private set; }
    public float? Value2 { get; private set; }

    public void ReadXml(XmlReader reader) {
        string attr1 = reader.GetAttribute("attr");
        string attr2 = reader.GetAttribute("attr2");
        reader.Read();

        Value1 = ConvertToNullable<int>(attr1);
        Value2 = ConvertToNullable<float>(attr2);
    }

    private static T? ConvertToNullable<T>(string inputValue) where T : struct {
        if ( string.IsNullOrEmpty(inputValue) || inputValue.Trim().Length == 0 ) {
            return null;
        }

        try {
            TypeConverter conv = TypeDescriptor.GetConverter(typeof(T));
            return (T)conv.ConvertFrom(inputValue);
        }
        catch ( NotSupportedException ) {
            // The conversion cannot be performed
            return null;
        }
    }

    public XmlSchema GetSchema() { return null; }
    public void WriteXml(XmlWriter writer) { throw new NotImplementedException(); }
}

class TestProgram {
    public static void Main(string[] args) {
        string xml = @"<root><elements><element attr='11' attr2='11.3'/><element attr='' attr2=''/></elements></root>";
        XmlSerializer deserializer = new XmlSerializer(typeof(DeserializeMe));
        Stream xmlStream = new MemoryStream(Encoding.ASCII.GetBytes(xml));
        var result = (DeserializeMe)deserializer.Deserialize(xmlStream);
    }
}
于 2009-08-20T09:18:27.107 回答
13

我自己最近一直在搞乱序列化,并且发现以下文章和帖子在处理值类型的空数据时很有帮助。

如何在 C# 中使用 XmlSerializer 使值类型可为空的答案- 序列化详细介绍了 XmlSerializer 的一个非常漂亮的技巧。具体来说,XmlSerialier 会查找 XXXSpecified 布尔属性以确定是否应包含它,这允许您忽略空值。

Alex Scordellis 提出了一个 StackOverflow 问题,得到了很好的回答。Alex 还在他的博客上写了一篇关于他试图解决的问题的文章。使用 XmlSerializer 反序列化为 Nullable<int>

Xsi:nil Attribute Binding Support上的 MSDN 文档也很有用。与IXmlSerializable Interface上的文档一样,尽管编写自己的实现应该是您最后的手段。

于 2009-08-18T18:57:22.920 回答
2

您也可以通过将 加载xml到 anXmlDocument然后将其反序列Json化以获取T您正在寻找的对象来做到这一点。

        public static T XmlToModel<T>(string xml)
        {

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);

            string jsonText = JsonConvert.SerializeXmlNode(doc);

            T result = JsonConvert.DeserializeObject<T>(jsonText);

            return result;
        }

于 2020-09-30T09:28:05.637 回答
2

想我不妨把我的答案扔进帽子里:通过创建实现 IXmlSerializable 接口的自定义类型解决了这个问题:

假设您有一个包含以下节点的 XML 对象:

<ItemOne>10</Item2>
<ItemTwo />

代表它们的对象:

public class MyItems {
    [XmlElement("ItemOne")]
    public int ItemOne { get; set; }

    [XmlElement("ItemTwo")]
    public CustomNullable<int> ItemTwo { get; set; } // will throw exception if empty element and type is int
}

动态可空结构表示任何潜在的可空条目以及转换

public struct CustomNullable<T> : IXmlSerializable where T: struct {
    private T value;
    private bool hasValue;

    public bool HasValue {
        get { return hasValue; }
    }

    public T Value {
        get { return value; }
    }

    private CustomNullable(T value) {
        this.hasValue = true;
        this.value = value;
    }

    public XmlSchema GetSchema() {
        return null;
    }

    public void ReadXml(XmlReader reader) {
        string strValue = reader.ReadString();
        if (String.IsNullOrEmpty(strValue)) {
            this.hasValue = false;
        }
        else {
            T convertedValue = strValue.To<T>();
            this.value = convertedValue;
            this.hasValue = true;
        }
        reader.ReadEndElement();

    }

    public void WriteXml(XmlWriter writer) {
        throw new NotImplementedException();
    }

    public static implicit operator CustomNullable<T>(T value) {
        return new CustomNullable<T>(value);
    }

}

public static class ObjectExtensions {
    public static T To<T>(this object value) {
        Type t = typeof(T);
        // Get the type that was made nullable.
        Type valueType = Nullable.GetUnderlyingType(typeof(T));
        if (valueType != null) {
            // Nullable type.
            if (value == null) {
                // you may want to do something different here.
                return default(T);
            }
            else {
                // Convert to the value type.
                object result = Convert.ChangeType(value, valueType);
                // Cast the value type to the nullable type.
                return (T)result;
            }
        }
        else {
            // Not nullable.
            return (T)Convert.ChangeType(value, typeof(T));
        }
    }
}
于 2017-01-16T23:12:51.657 回答