XMLSerializer在序列化时会忽略DataAnnotations

时间:2018-10-22 13:38:33

标签: c# xmlserializer xsd.exe

我正在使用xsd.exe在我们的项目中创建C#类。

此方法运行良好,但似乎忽略了以下限制:

<xs:element name="TestClass">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="testString">
                <xs:simpleType>
                    <xs:restriction base="xs:string">
                        <xs:maxLength value="6"/>
                    </xs:restriction>
                </xs:simpleType>
            </xs:element>
        </xs:sequence>
    </xs:complexType>
</xs:element>

因此,我尝试将属性手动添加到生成的类中的这些属性中:

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.81.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = 
"http://www.mynamespace.org")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = 
"http://www.mynamespace.org", IsNullable = false)]
public partial class TestClass
{
     [System.Xml.Serialization.XmlElementAttribute(DataType = "NMTOKEN")]
     [Required, StringLength(6, MinimumLength = 6, ErrorMessage = 
      "StringLength test")]
     public string testString { get; set; }
 }

问题是XmlSerializer在序列化/反序列化时会忽略这些属性。不需要,也不在乎字符串的长度。

xsd.exe生成了XmlElementAttribute。

我添加了Required和StringLength属性。

我应该如何实现我的目标?

0 个答案:

没有答案
相关问题