Can I fail to deserialize with XmlSerializer in C# if an element is not found?

后端 未结 3 1587
天命终不由人
天命终不由人 2020-11-30 11:19

I am using XmlSerializer to write and read an object to xml in C#. I currently use the attributes XmlElement and XmlIgnore to manipulate the seria

3条回答
  •  猫巷女王i
    2020-11-30 11:55

    The only way I've found to do this is via XSD. What you can do is validate while you deserialize:

    static T Deserialize(string xml, XmlSchemaSet schemas)
    {
        //List exceptions = new List();
        ValidationEventHandler validationHandler = (s, e) =>
        {
            //you could alternatively catch all the exceptions
            //exceptions.Add(e.Exception);
            throw e.Exception;
        };
    
        XmlReaderSettings settings = new XmlReaderSettings();
        settings.Schemas.Add(schemas);
        settings.ValidationType = ValidationType.Schema;
        settings.ValidationEventHandler += validationHandler;
    
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        using (StringReader sr = new StringReader(xml))
            using (XmlReader books = XmlReader.Create(sr, settings))
               return (T)serializer.Deserialize(books);
    }
    

提交回复
热议问题