xmlserializer validation

后端 未结 2 1236
难免孤独
难免孤独 2020-12-01 19:01

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 n

2条回答
  •  难免孤独
    2020-12-01 19:43

    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.

提交回复
热议问题