0

I've got an XSD which has been supplied by a third party and I've then converted this into classes using xsd.exe.

Due to the fact we do not own this XSD, I'm trying to not alter the generated classes in any way.

Without manually applying a blank string check to every single field we are mapping, e.g.:

!String.IsNullOrWhiteSpace(field) ? field : null;

I can't think of an easy way to serialise the blank strings in a way which means they are not output at all (no tag is produced).

The reason we cannot output blank strings is because the XSD has pattern constraints such as StringM50m1 which I believe means a minimum length of 1 is required (however, they are happy to not receive the tag if there is no content) which fail post-output validation with the following message:

The 'field' element is invalid - The value '' is invalid according to its datatype 'StringM50m1' - The Pattern constraint failed.

Any thoughts would be appreciated.

Sir Rufo
  • 18,395
  • 2
  • 39
  • 73
Danny Lager
  • 371
  • 1
  • 4
  • 17
  • 1
    Take a look here https://stackoverflow.com/questions/5818513/xml-serialization-hide-null-values – Samvel Petrosov Jun 07 '17 at 07:27
  • It's an interesting approach however it looks like I would have to generate a function for every single field? there are a lot of fields! thanks – Danny Lager Jun 07 '17 at 07:30

1 Answers1

0

If you use XmlSerializer you can add XmlDefaultValue for required properties:

private static void Serialize()
{
    XsdClass xc = new XsdClass();
    xc.SomeString1 = string.Empty;
    xc.SomeString2 = "value";
    xc.SomeString3 = null;

    XmlAttributeOverrides overrides = new XmlAttributeOverrides();
    XmlAttributes attribs = new XmlAttributes();
    attribs.XmlDefaultValue = string.Empty;
    foreach (var prop in TypeDescriptor.GetProperties(typeof(XsdClass)).Cast<PropertyDescriptor>().Where(x => !x.IsReadOnly && x.PropertyType == typeof(string)))
        overrides.Add(typeof(XsdClass), prop.Name, attribs);

    XmlSerializer serializer = new XmlSerializer(typeof(XsdClass), overrides);
    string result;
    using (StringWriter textWriter = new StringWriter())
    {
        serializer.Serialize(textWriter, xc);
        result = textWriter.ToString();
    }
}

public class XsdClass 
{
    public string SomeString1 { get; set; }
    public string SomeString2 { get; set; }
    public string SomeString3 { get; set; }
}
Pablo notPicasso
  • 3,031
  • 3
  • 17
  • 22