English 中文(简体)
xmlserializer validation
原标题:

I m using XmlSerializer to deserialize Xml achives. But I found the class xsd.exe generated only offers capability to read the xml, but no validation. For example, if one node is missing in a document, the attribute field of the generated class will be null, rather than throws a validation exception as I expected. How can I achieve that? Thanks!

最佳回答

The following code should validate against a schema while deserializing. Similar code can be used to validate against a schema while serializing.

private static Response DeserializeAndValidate(string tempFileName)
{
    XmlSchemaSet schemas = new XmlSchemaSet();
    schemas.Add(LoadSchema());

    Exception firstException = null;

    var settings = new XmlReaderSettings
                   {
                       Schemas = schemas,
                       ValidationType = ValidationType.Schema,
                       ValidationFlags =
                           XmlSchemaValidationFlags.ProcessIdentityConstraints |
                           XmlSchemaValidationFlags.ReportValidationWarnings
                   };
    settings.ValidationEventHandler +=
        delegate(object sender, ValidationEventArgs args)
        {
            if (args.Severity == XmlSeverityType.Warning)
            {
                Console.WriteLine(args.Message);
            }
            else
            {
                if (firstException == null)
                {
                    firstException = args.Exception;
                }

                Console.WriteLine(args.Exception.ToString());
            }
        };

    Response result;
    using (var input = new StreamReader(tempFileName))
    {
        using (XmlReader reader = XmlReader.Create(input, settings))
        {
            XmlSerializer ser = new XmlSerializer(typeof (Response));
            result = (Response) ser.Deserialize(reader);
        }
    }

    if (firstException != null)
    {
        throw firstException;
    }

    return result;
}
问题回答

The following code will manually load and validate your XML against a schema file programmatically, allowing you to deal with any resulting errors and/or warnings.

//Read in the schema document
using (XmlReader schemaReader = XmlReader.Create("schema.xsd"))
{
    XmlSchemaSet schemaSet = new XmlSchemaSet();

    //add the schema to the schema set
    schemaSet.Add(XmlSchema.Read(schemaReader, 
    new ValidationEventHandler(
        delegate(Object sender, ValidationEventArgs e)
        {
        }    
    )));

    //Load and validate against the programmatic schema set
    XmlDocument xmlDocument = new XmlDocument();
    xmlDocument.Schemas = schemaSet;
    xmlDocument.Load("something.xml");

    xmlDocument.Validate(new ValidationEventHandler(
        delegate(Object sender, ValidationEventArgs e)
        {
            //Report or respond to the error/warning
        }
    )); 
 }

Now obviously you desire to have the classes generated by xsd.exe to do this automatically and while loading (the above approach would require a second handling of the XML file), but a pre-load validate would allow you to programmatically detect a malformed input file.





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签