проверка xmlserializer

На самом деле я вчера запустил эти тесты, но становилось поздно, таким образом, я не помещал свои ответы.

нижняя строка кажется, что они берут обоих то же время в среднем. Я сделал тест более чем 100 000 повторений.

я попробую StringBuilder также, и я отправлю код и результаты, когда я возвращусь домой.

11
задан Roy 10 November 2009 в 03:14
поделиться

2 ответа

Следующий код должен проверяться на соответствие схеме при десериализации. Аналогичный код можно использовать для проверки соответствия схеме во время сериализации.

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;
}
31
ответ дан 3 December 2019 в 01:44
поделиться

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.

6
ответ дан 3 December 2019 в 01:44
поделиться
Другие вопросы по тегам:

Похожие вопросы: