1

I am using xsd.exe to create C# classes in our project.

This is working well, except it seems to ignore restrictions like the following:

<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>

So, I am trying to manually add attributes to these properties in the generated classes:

[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; }
 }

The problem is XmlSerializer is ignoring these attributes when serializing / deserializing. It does not require, and it does not care about the length of the string.

xsd.exe generated the XmlElementAttribute.

I added the Required and StringLength attributes.

How should I accomplish my goal?

MattCash
  • 81
  • 2
  • 9
  • You can validate against a schema while deserializing as shown in [xmlserializer validation](https://stackoverflow.com/q/1705430). In fact I think this is a duplicate. Agree? – dbc Oct 22 '18 at 16:48
  • @dbc Agreed! I tried to find something like this several times with no luck. – MattCash Oct 22 '18 at 19:45

0 Answers0