Getting started with XSD validation with .NET

前端 未结 3 1660
鱼传尺愫
鱼传尺愫 2020-12-14 09:27

Here is my first attempt at validating XML with XSD.

The XML file to be validated:




        
3条回答
  •  情书的邮戳
    2020-12-14 09:56

    Your code to extract the schema location looks weird. Why do you get the value of the xmlns attribute and concatenate it with the value of the xsi:noNamespaceSchemaLocation attribute? The exception is caused by the fact that you cannot specify a prefix in a call to Attributes; you need to specify the desired XNamespace.

    Try this (untested):

    // Load document
    XDocument doc = XDocument.Load("file.xml");
    
    // Extract value of xsi:noNamespaceSchemaLocation
    XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
    string schemaURI = (string)doc.Root.Attribute(xsi + "noNamespaceSchemaLocation");
    
    // Create schema set
    XmlSchemaSet schemas = new XmlSchemaSet();
    schemas.Add("Schemas", schemaURI);
    
    // Validate
    doc.Validate(schemas, (o, e) =>
                          {
                              Console.WriteLine("{0}", e.Message);
                          });
    

提交回复
热议问题