Home > Software engineering >  How to get xml Schema validation working on .net 6
How to get xml Schema validation working on .net 6

Time:08-15

I have 2 console apps with the identical code to validate xml. The schema is complex so I can't post it here but I can post my validation code that works on .net 4.7 bot not 6.

using System;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;

namespace ValidateXmlNet5

{
    internal class Program
    {
        private static bool isValidate = true;

        private static void Main(string[] args)
        {
            Console.WriteLine("XML File Validation Started................");
            Program.Validate();
            Console.WriteLine("XML File Validation Ended................");
        }

        private static void Validate()
        {
            try
            {
                string appSetting1 = "C:\\Documents\\Test\\finalOutput";
                string appSetting2 = @"C:\Documents\Test2\claw.xsd";
                string appSetting3 = "http://www.something.com/xmlschemas/content/lb/claw/1/";
                XmlSchemaSet schemas = new XmlSchemaSet();
                DirectoryInfo directoryInfo = new DirectoryInfo(appSetting1);
                schemas.Add(appSetting3, appSetting2);
                foreach (FileInfo file in directoryInfo.GetFiles("*.xml", SearchOption.AllDirectories))
                {
                    XDocument source = XDocument.Load(XmlReader.Create(file.FullName));
                    Program.isValidate = true;
                    source.Validate(schemas, new ValidationEventHandler(Program.ValidationEventHandler));
                    if (Program.isValidate)
                    {
                        Console.WriteLine(string.Format("File {0} Validated Successfully.", (object)file.FullName));
                    }
                    else
                    {

                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();
        }

        private static void ValidationEventHandler(object sender, ValidationEventArgs e)
        {
            if (e.Severity != XmlSeverityType.Error)
                return;
            Console.WriteLine(e.Message);
        }
    }
}

on .net 6 I get the error: Reference to undeclared model group... It doesn't seem to like groups. When I comment out the group it complains about another group

Arbitrary example of group below:

 <xs:group name="A">
    <xs:sequence>
      <xs:group ref="NS:A.B"/>
    </xs:sequence>
  </xs:group>

Thank you

CodePudding user response:

I think the issue you are experiencing can be related to https://github.com/dotnet/runtime/issues/29346#issuecomment-485798826 so try to set schemas.XmlResolver = new XmlUrlResolver(); explicitly.

  • Related