1

I'm trying to serialize a XML file to an object, when deleting a XML tag, I'm expecting an exception because my XML file is not valid any more, but I still get my data object with deleted tag (property) is null. How to make this specific tag required so when trying to serialize it, it will throw an exception saying tag xxx is missing => XML file is not valid => so data object is also null.

My XSD

...
<xs:element name="Language" minOccurs="1" maxOccurs="1">
...

My XML

<?xml version="1.0" encoding="iso-8859-1"?>
<root>
  <item>
    <sub1>1037</sub1>
    <Language>F</Language><!-- If I delete this tag, my XML file should be invalid -->
    <sub1>ZDC</sub1>
  </item>
 <root>

My serialize boject

...
        /// <remarks/>
        public string Language
        {
            get
            {
                return this.languageField;
            }
            set
            {
                this.languageField = value;
            }
        }
...
Stacked
  • 6,892
  • 7
  • 57
  • 73
  • 4
    Check out [Can I fail to deserialize with XmlSerializer in C# if an element is not found?](http://stackoverflow.com/questions/259726/can-i-fail-to-deserialize-with-xmlserializer-in-c-sharp-if-an-element-is-not-fou) – Lloyd Sep 12 '13 at 12:50
  • 2
    Why not validate yourself before serialization? – Rotem Sep 12 '13 at 12:51
  • I've generated my serialize object with xsd.exe using the XSD file and I thought minOccurs="1" maxOccurs="1" will do the trick to make my tag required but it did not! How to make my property 'Language' required using attributes or something like that? – Stacked Sep 12 '13 at 12:56
  • @Stacked that's part of things xsd.exe ignore, that and `xs:pattern` or xsd includes, basically when it comes to validating the content rather than the structure of an xml file, you will pretty much have to do it yourself when you serialize – Simon Rapilly Sep 12 '13 at 13:13

1 Answers1

2

I ended up with adding the XSD files to my solution as Embedded Resource and using this method:

public static void ValidateXmlFile<T>(string file, string xsdPath)
{
    var assembly = typeof(T).Assembly;
    var assName = assembly.GetName().Name;
    var xsdFullPath = String.Format("{0}.{1}", assName, xsdPath);
    var schema = assembly.GetManifestResourceStream(xsdFullPath);
    if (schema == null)
        throw new Exception(String.Format("{0} could not be validated, the XSD schema {1} not found", file, xsdFullPath));
    var xmlIsValid = true;
    var errorMsg = String.Empty;
    var schemaReader = XmlReader.Create(schema);
    var settings = new XmlReaderSettings();
    settings.Schemas.Add(null, schemaReader);
    settings.ValidationType = ValidationType.Schema;
    settings.ValidationEventHandler += (sender, args) =>
    {
        xmlIsValid = false;
        errorMsg = args.Message;
    };

    using (var stream = new FileStream(file, FileMode.Open))
    {
        var xr = XmlReader.Create(stream, settings);
        while (xr.Read()) { }
        if (!xmlIsValid) throw new Exception(String.Format("XML file {0} is not valid: {1}", file, errorMsg));
    }
}

When errors are found, an exception is thrown with the details about the error.

Stacked
  • 6,892
  • 7
  • 57
  • 73