C# xml 序列化必填字段 [英] C# xml serialization required field

查看:83
本文介绍了C# xml 序列化必填字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一些字段标记为需要写入 XML 文件,但没有成功.我有一个包含约 30 个属性的配置类,这就是为什么我不能像这样封装所有属性

I need to mark some fields as required to be writen in XML file, but no success. I have a configuration class with ~30 properties, this is why i cannot envelope all properties like this

    public string SomeProp
    {
        get { return _someProp; }
        set
        {
            if (_someProp == null)
                throw  new ArgumentNullException("value");
            _someProp = value;
        }
    }

和 null 是来自代码的有效值,但不是来自 XML 的值.我正在尝试使用 XmlAttribute,但它并没有像我预期的那样影响(反序列化时出现 IOException).

and null is valid value from code, but not from XML. I'm trying to use XmlAttribute, but it doesn't affect like I expected (IOException when deserialising).

例如这段代码:

    [XmlElement(IsNullable = true)]
    public String Name { get; set; }

    [XmlElement(IsNullable = true)]
    public String Description { get; set; }

NameDescription 标签缺失时非常有效.

is pretty valid when Name and Description tags are missing.

澄清:

类:

public class MyClass
{
    [XmlElement(IsNullable = true)]
    public String Name { get; set; }

    [XmlElement(IsNullable = true)]
    public String Description { get; set; } 
}

XML:

<?xml version="1.0"?>
<MyClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>hello</Name>
</MyClass>

代码:

MyClass deserialize = (MyClass)new XmlSerializer(my.GetType()).Deserialize(new FileStream("result.xml", FileMode.Open));
Console.WriteLine(deserialize.Name);
Console.WriteLine(deserialize.Description);

结果:反序列化成功,描述为空

预期:异常,未找到描述标签.

推荐答案

你必须使用 XmlSerializer 吗?DataContractSerializer 提供以下选项:

Do you have to use XmlSerializer? DataContractSerializer provides the following option:

[DataMember(IsRequired = true)]

这篇关于C# xml 序列化必填字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆