Compile schemas with xsd files included

I have a static method that I use to validate an XML file against an XSD file. This works great until an XSD file appears, which includes another XSD file.

Example when I had problems:

TYPES.XSD:

<xs:simpleType name="MY_AMOUNT">
    <xs:restriction base="xs:decimal">
        <xs:maxInclusive value="999999999999.99"/>
        <xs:minInclusive value="-999999999999.99"/>
        <xs:totalDigits value="14"/>
        <xs:fractionDigits value="2"/>
    </xs:restriction>
</xs:simpleType>

MAIN.XSD:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
    <xs:include schemaLocation="TYPES.xsd"/>
    <xs:element name="ROOT">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="SOMEREF1"/>
                <xs:element ref="SOMEREF2"/>
                <xs:element name="AMOUNT" type="MY_AMOUNT" minOccurs="0"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

VALIDATION CODE:

public static class XmlUtils
{
    private static string Errors = string.Empty;

    public static bool ValidateAgainstXSD(string xmlFilePath, string xsdFilePath, ref string message)
    {
        try
        {
            var settings = new XmlReaderSettings();

            settings.ValidationType = ValidationType.Schema;
            settings.ValidationFlags = XmlSchemaValidationFlags.ProcessInlineSchema
                | XmlSchemaValidationFlags.ProcessInlineSchema
                | XmlSchemaValidationFlags.ReportValidationWarnings;
            settings.Schemas.Add(null, xsdFilePath);
            settings.Schemas.Compile();

            settings.ValidationEventHandler += (sender, args) =>
            {
                if (args.Severity == XmlSeverityType.Error)
                {
                    Errors += args.Message + "\n";
                }
            };

            using (var reader = XmlReader.Create(xmlFilePath, settings))
            {
                while (reader.Read()) { }
            }

            message = Errors ?? string.Empty;
            return string.IsNullOrEmpty(Errors);
        }
        catch (Exception e)
        {
            message = "# error validating xml file: " + e.Message;
            return false;
        }
    }
}

Somehow it seems that I should indicate the path to the included XSD file, but I have no idea where.

The error occurs when settings.Schemas.Compile();it says that the type "MY_AMOUNT" is not declared. I read about custom XmlResolvers, but to be honest, I have not received this.

If this is important for the answer: xsd files are always in the same directory!

The method is called like this:

string msg = string.Empty;
string basedir = @"C:\Temp";
string xml = Path.Combine(basedir, "XML_FILE.xml");
string xsd = Path.Combine(basedir, "MAIN.xsd");

if (XmlUtils.ValidateAgainstXSD(xml, xsd, ref msg))
{
    // do some work
}
else
{
    Console.WriteLine(msg);
}

Console.ReadLine();

Any help is much appreciated - Thank you!

UPDATE 2016-12-05:

I wrote my own XmlUrlResolver to see what happens behind the scenes:

internal class XUrlResolver : XmlUrlResolver
{
    public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)
    {
        return base.GetEntity(absoluteUri, role, ofObjectToReturn);
    }

    public override Uri ResolveUri(Uri baseUri, string relativeUri)
    {
        return base.ResolveUri(baseUri, relativeUri);
    }
}

:

XmlSchemaSet xset = new XmlSchemaSet();
xset.XmlResolver = new XUrlResolver();
xset.Add("", xsdFilePath);
xset.Compile();

( xset.Add):

  • XmlUrlResolver.ResolveUri(null,"C:\\Temp\\MAIN.XSD"){file:///C:/Temp/MAIN.xsd}
  • XmlUrlResolver.ResolveUri(null,"C:\\Temp\\MAIN.XSD"){file:///C:/Temp/MAIN.xsd}
  • XmlUrlResolver.GetEntity({file:///C:/Temp/MAIN.xsd}) → Filestream to MAIN.xsd
  • XmlUrlResolver.ResolveUri({file:///C:/Temp/MAIN.xsd},"TYPES.XSD"){file:///C:/Temp/TYPES.xsd}
  • XmlUrlResolver.GetEntity({file:///C:/Temp/TYPES.xsd}) → Filestream to TYPES.xsd

( !?!) - TYPES.XSD , .

, xset.Compile() : " MY_AMOUNT "

, :/

+4
2

xsd .

Types.xsd( xs)

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:simpleType name="MY_AMOUNT">
    <xs:restriction base="xs:decimal">
        <xs:maxInclusive value="999999999999.99"/>
        <xs:minInclusive value="-999999999999.99"/>
        <xs:totalDigits value="14"/>
        <xs:fractionDigits value="2"/>
    </xs:restriction>
</xs:simpleType>
</xs:schema>

Main.xsd( ).

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
    <xs:include schemaLocation="TYPES.xsd"/>
    <xs:element name="ROOT">
        <xs:complexType>
            <xs:sequence>                
                <xs:element name="AMOUNT" type="MY_AMOUNT" minOccurs="0"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

, , xsd , .

+2

.

, , , Environment.CurrentDirectory , XSD. .

0

Source: https://habr.com/ru/post/1662545/


All Articles