0

I'm stumped on why I can't validate the XML file to a schema and then deserialize the xml into an class.

I can do either or. i.e. if I comment out the ValidateXML then the ConvertToObject works and vice versa. If leave both in that I get an error : "There is an error in XML document (0, 0)" (Usually when I get this error I usually have left the document open prior to deserializing it.

My main logic

foreach (var myFile in Directory.EnumerateFiles(@"C:MyFolder", "*.xml"))
            {
                try
                {
                    using (var fileStream = new FileStream(myFile, FileMode.Open, FileAccess.Read))
                    {
                        if (ValidateXML(fileStream))
                        {
                            CreateObjects(fileStream);
                            goodCounter++;
                        }
                        else
                        {
                            sb.AppendLine("Validation failed for: " + myFile);
                            badCounter++;
                        }
                    }
                }
                catch
                {
                    sb.AppendLine(myFile);
                }
            }

My validate method:

private bool ValidateXML(Stream stream)
{
    try
    {
        XmlDocument xDoc = new XmlDocument();
        xDoc.Load(stream);
        xDoc.Schemas.Add(null, @"C:My_XSD.xsd");

        ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);
        xDoc.Validate(eventHandler);

        return true;
    }
    catch
    {
        return false;
    }
}
    static void ValidationEventHandler(object sender, ValidationEventArgs e)
    {
        switch (e.Severity)
        {
            case XmlSeverityType.Error:
                //Console.WriteLine("Error: {0}", e.Message);
                throw new Exception(e.Message);
                //break;
            case XmlSeverityType.Warning:
                //Console.WriteLine("Warning {0}", e.Message);
                throw new Exception(e.Message);
                //break;
        }

    }
John Doe
  • 3,053
  • 17
  • 48
  • 75
  • 2
    You might need to set the position of the filestream back to origin before trying to create your object from it. – Kevin Jun 27 '16 at 18:18
  • You can deserialize directly from your `XmlDocument` using `XmlNodeReader`. See [Deserialize object property with StringReader vs XmlNodeReader](https://stackoverflow.com/questions/30102275/deserialize-object-property-with-stringreader-vs-xmlnodereader) or [How to initialize `XmlElement[]`?](https://stackoverflow.com/questions/32805732/how-to-initialize-xmlelement). – dbc Jun 27 '16 at 18:44

1 Answers1

0

Kevin was right...

fileStream.Seek(0, SeekOrigin.Begin);
John Doe
  • 3,053
  • 17
  • 48
  • 75