Question

In my code I have the following class to deserialize XML:

public abstract class AssetBase
{
    [XmlAttribute] public string Name { get; set; }
    [XmlAttribute] public float RelativeX { get; set; }
    [XmlAttribute] public float RelativeY { get; set; }
    [XmlAttribute] public float RelativeZ { get; set; }
    [XmlAttribute] public float ScaleX { get; set; }
    [XmlAttribute] public float ScaleY { get; set; }
    [XmlAttribute] public bool Visible { get; set; }
}

When I use xsd.exe to define a schema for this, the schema sets it up so these properties are required for validation.

How can I set this class up so that these can be left empty by the user, as not all of these are mandatory?


Edit: I just looked at the xsd it generated and saw:

  <xs:complexType name="AssetBase" abstract="true">
    <xs:attribute name="Name" type="xs:string" />
    <xs:attribute name="RelativeX" type="xs:float" use="required" />
    <xs:attribute name="RelativeY" type="xs:float" use="required" />
    <xs:attribute name="RelativeZ" type="xs:float" use="required" />
    <xs:attribute name="ScaleX" type="xs:float" use="required" />
    <xs:attribute name="ScaleY" type="xs:float" use="required" />
    <xs:attribute name="Visible" type="xs:boolean" use="required" />
  </xs:complexType>

I'm confused as to why Name isn't set to be required but the rest are...

Was it helpful?

Solution

As you have discovered yourself Nullable<T> doesn't just work with [XmlAttribute] as it's a complex type. You'll have to use the 'magic' property *Specified to deal with this.

[XmlIgnore]
public float? RelativeX
{
    get { return this.RelativeX; }
    set { this.RelativeX = value; }
}

[XmlAttribute("RelativeX")]
public float RelativeXValue
{
    get { return this.RelativeX.Value; }
    set { this.RelativeX = value; }
}

[XmlIgnore]
public bool RelativeXValueSpecified
{
    get { return this.RelativeX.HasValue; }
}

Your other options are:

  • Use strings for all of your attributes and have corresponding properties of the right type
  • Implement IXmlSerializable

OTHER TIPS

I found this explanation :

Use Attribute: Generating an XML Schema document from classes

In either of the following two cases, Xsd.exe does not specify the use attribute, reverting to the default value optional:

• An extra public bool field that follows the Specified naming convention is present.

• A default value is assigned to the member via an attribute of type System.ComponentModel.DefaultValueAttribute.

If neither of these conditions is met, Xsd.exe produces a value of required for the use attribute.

From this article

I used the default value way and it works fine :)

Enjoy !!!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top