XML validate using XSDs with imports and includes in .net core

2

I want to validate XML documents against xsds with includes and imports, without includes and imports this code work. These are 4 xsds used to validate xml.

Main.xsd

<?xml version="1.0" encoding="utf-8"?>
<xs:schema  xmlns:ord="http://NamespaceTest.com/OrderTypes"
xmlns:pur="http://NamespaceTest.com/Purchase"
xmlns:cmn="http://NamespaceTest.com/CommonTypes"
xmlns:cust="http://NamespaceTest.com/CustomerTypes"
targetNamespace="http://NamespaceTest.com/Purchase"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
<xs:import  schemaLocation="CommonTypes.xsd"
namespace="http://NamespaceTest.com/CommonTypes" />
<xs:import  schemaLocation="CustomerTypes.xsd"
namespace="http://NamespaceTest.com/CustomerTypes" />
<xs:import  schemaLocation="OrderTypes.xsd"
namespace="http://NamespaceTest.com/OrderTypes" />
<xs:element  name="Purchase">
<xs:complexType>
<xs:sequence>
<xs:element  name="OrderDetail"  type="ord:OrderType" />
<xs:element  name="PaymentMethod"  type="cmn:PaymentMethodType" />
<xs:element  ref="pur:CustomerDetails" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element  name="CustomerDetails"  type="cust:CustomerType" />
</xs:schema>

CommonTypes.xsd

<?xml version="1.0" encoding="utf-8"?>
<xs:schema  targetNamespace="http://NamespaceTest.com/CommonTypes"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
<xs:complexType  name="AddressType">
<xs:sequence>
<xs:element  name="Line1"  type="xs:string" />
<xs:element  name="Line2"  type="xs:string" />
</xs:sequence>
</xs:complexType>
<xs:simpleType  name="PriceType">
<xs:restriction  base="xs:decimal">
<xs:fractionDigits  value="2" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType  name="PaymentMethodType">
<xs:restriction  base="xs:string">
<xs:enumeration  value="VISA" />
<xs:enumeration  value="MasterCard" />
<xs:enumeration  value="Cash" />
<xs:enumeration  value="AMEX" />
</xs:restriction>
</xs:simpleType>
</xs:schema>

CustomerTypes.xsd

<?xml version="1.0" encoding="utf-8"?>
<xs:schema  xmlns:cmn="http://NamespaceTest.com/CommonTypes"
targetNamespace="http://NamespaceTest.com/CustomerTypes"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
<xs:import  schemaLocation="CommonTypes.xsd"
namespace="http://NamespaceTest.com/CommonTypes" />
<xs:complexType  name="CustomerType">
<xs:sequence>
<xs:element  name="Name"  type="xs:string" />
<xs:element  name="DeliveryAddress"  type="cmn:AddressType" />
<xs:element  name="BillingAddress"  type="cmn:AddressType" />
</xs:sequence>
</xs:complexType>
</xs:schema>

OrderTypes.xsd

<?xml version="1.0" encoding="utf-8"?>
<xs:schema  xmlns:cmn="http://NamespaceTest.com/CommonTypes"
targetNamespace="http://NamespaceTest.com/OrderTypes"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
<xs:import  schemaLocation="CommonTypes.xsd"
namespace="http://NamespaceTest.com/CommonTypes" />
<xs:complexType  name="OrderType">
<xs:sequence>
<xs:element  maxOccurs="unbounded"  name="Item">
<xs:complexType>
<xs:sequence>
<xs:element  name="ProductName"  type="xs:string" />
<xs:element  name="Quantity"  type="xs:int" />
<xs:element  name="UnitPrice"  type="cmn:PriceType" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:schema>

This is xml going to validate

<?xml version="1.0" encoding="utf-8"?>
  <CustomerDetails>
    <Name>Peter James</Name>
    <DeliveryAddress>
      <Line1>141 Saint Carmen</Line1>
      <Line2>Zeel Street, MA, US</Line2>
    </DeliveryAddress>
    <BillingAddress>
      <Line1>142 Saint Carmen</Line1>
      <Line2>Zeel Street, MA, US</Line2>
    </BillingAddress>
  </CustomerDetails>

I got this error when going to validate xml

  System.Xml.Schema.XmlSchemaException: 'Type 'http://NamespaceTest.com/CustomerTypes:CustomerType' is not declared.'

Code snippet use to validate

using System;
using System.Xml;
using System.Xml.Schema;

namespace ConsoleApp3
{
    class XmlValidatorTest
    {
        static void Main()
        {
            Console.WriteLine("Start XML Validator.....");

            // Create the XmlSchemaSet class.
            XmlSchemaSet sc = new XmlSchemaSet();

            // Add the schema to the collection.
            sc.Add("http://NamespaceTest.com/Purchase", "test_xml_schemas/Main.xsd");
            sc.Compile();

            foreach (XmlSchema schema in sc.Schemas())
            {
                Console.WriteLine(schema.TargetNamespace);
            }

            // Set the validation settings.
            XmlReaderSettings setting = new XmlReaderSettings();
            setting.Schemas.Add(sc);
            setting.ValidationType = ValidationType.Schema;
            setting.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
            setting.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;

            setting.ValidationEventHandler += new ValidationEventHandler(Handler);

            using (XmlReader validationReader = XmlReader.Create("test_xmls/CustomerDetails01.xml", setting))
            {
                while (validationReader.Read())
                {
                    /* do nothing for while */
                }
            }

            Console.ReadLine();
        }

        // Display any validation errors.
        private static void Handler(object sender, ValidationEventArgs e)
        {
            if (e.Severity == XmlSeverityType.Error ||
                e.Severity == XmlSeverityType.Warning)
            {
                Console.WriteLine(String.Format("Line: {0}, Position: {1} '{2}'",
                    e.Exception.LineNumber, e.Exception.LinePosition, e.Exception.Message));

            }
        }
    }
}

Validating xml against an xsd that has include and import in c# I try this also got this error:

System.Xml.Schema.XmlSchemaException
  HResult=0x80131941
  Message=The targetNamespace 'http://NamespaceTest.com/Purchase' of included/redefined schema should be the same as the targetNamespace '' of the including schema.
  Source=System.Private.Xml
  StackTrace:
   at System.Xml.Schema.XmlSchemaSet.InternalValidationCallback(Object sender, ValidationEventArgs e)
   at System.Xml.Schema.BaseProcessor.SendValidationEvent(XmlSchemaException e, XmlSeverityType severity)
   at System.Xml.Schema.BaseProcessor.SendValidationEvent(String code, String msg1, String msg2, XmlSchemaObject source)
   at System.Xml.Schema.Preprocessor.Preprocess(XmlSchema schema, String targetNamespace, ArrayList imports)
   at System.Xml.Schema.Preprocessor.Execute(XmlSchema schema, String targetNamespace, Boolean loadExternals)
   at System.Xml.Schema.XmlSchemaSet.PreprocessSchema(XmlSchema& schema, String targetNamespace)
   at System.Xml.Schema.XmlSchemaSet.Add(String targetNamespace, XmlSchema schema)
   at System.Xml.Schema.XmlSchemaSet.Add(XmlSchema schema)
   at ConsoleApp3.XmlValidator.Main() in D:\App\ConsoleApp3\ConsoleApp3\XmlValidator.cs:line 29
.net
xml
xsd
asked on Stack Overflow Sep 16, 2019 by Dulkith Bataduwa • edited Sep 16, 2019 by zx485

1 Answer

1

I had similar issue and i resolved it by adding

sc.XmlResolver = new XmlUrlResolver();

to my code just prior to adding schema to collection

XmlSchemaSet sc = new XmlSchemaSet();

// Add url resolver to fix the issue
sc.XmlResolver = new XmlUrlResolver();
// Add the schema to the collection.
sc.Add("http://NamespaceTest.com/Purchase", "test_xml_schemas/Main.xsd");
sc.Compile();

i followed different behavior for Full Framework and .NET Core for xml schema compilation

answered on Stack Overflow May 26, 2020 by Virat Sarswat

User contributions licensed under CC BY-SA 3.0