Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML validation by XSD: Could not find schema information for the element

There is a XML:

<?xml version="1.0" encoding="utf-8" ?>
 <FirstSection FirstSectionAttr="5" >
   <SecondSection Value="0x15"/>
   <SecondSection Value="10"/>
 </FirstSection>

There is a XSD (was created by VS):

<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="FirstSection">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" name="SecondSection">
          <xs:complexType>
            <xs:attribute name="Value" type="xs:string" use="required" />
          </xs:complexType>
        </xs:element>
      </xs:sequence>
      <xs:attribute name="FirstSectionAttr" type="xs:unsignedByte" use="required" />
    </xs:complexType>
  </xs:element>
</xs:schema>

There is a code to validate:

    static void Validate(string xsdPath, string fullFileName)
    {
        try
        {
            var settings = new XmlReaderSettings();
            settings.Schemas.Add("http://www.w3.org/2001/XMLSchema", xsdPath);
            settings.ValidationType = ValidationType.Schema;
            settings.ValidationEventHandler += OnXmlValidationEventError;
            settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;

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

                }
            }
        }
        catch (Exception exception)
        {
            Console.WriteLine(exception);
        }

    }

    private static void OnXmlValidationEventError(object sender, ValidationEventArgs e)
    {
        try
        {
            Console.WriteLine("Problem: " + e.Message);
        }
        catch (Exception exception)
        {
            Console.WriteLine(exception);
        }
    }

The code returns:

Problem: Could not find schema information for the element 'FirstSection'.

Problem: Could not find schema information for the attribute 'FirstSectionAttr'.

Problem: Could not find schema information for the element 'SecondSection'.

Problem: Could not find schema information for the attribute 'Value'.

Problem: Could not find schema information for the element 'SecondSection'.

Problem: Could not find schema information for the attribute 'Value'.

How to validate it correctly?

like image 833
Andrej B. Avatar asked Dec 25 '22 18:12

Andrej B.


1 Answers

Either add a default namespace to your document

<FirstSection FirstSectionAttr="5" xmlns="http://www.w3.org/2001/XMLSchema">

Or register your schema without a namespace

settings.Schemas.Add(null, xsdPath);
like image 106
Ovidiu Avatar answered Dec 29 '22 12:12

Ovidiu