How can I validate the output of XmlSerializer?

 ̄綄美尐妖づ 提交于 2019-12-05 08:12:47

What about reading it in again using a validating reader

Here's a quick stab at it

Stream stream = new MemoryStream(Encoding.UTF8.GetBytes("<YourXml />"));
var input = mappingAssembly.GetManifestResourceStream(
            "MySchema.xsd"
            ); //This could be whatever resource your schema is           
var schemas = new XmlSchemaSet();            
schemas.Add(
   "urn:YourSchemaUrn",
   XmlReader.Create(
      input
      )
 );

var settings = new XmlReaderSettings
                           {
                               ValidationType = ValidationType.Schema,
                               Schemas = schemas
                           };

settings.ValidationEventHandler += MakeAHandlerToHandleAnyErrors;

var reader = XmlReader.Create(stream, settings);
while (reader.Read()) {} //Makes it read to the end, therefore validates

You'll need to have some handler to do something when there are errors.

You could use XmlReader to validate a XML file against an XSD schema.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!