0

I have created a library to validate the XML file with the XSD file using XmlReaderSettings. It works fine until the user fills data in the XSD file then changes XSD extension to XML and uses the library to validate them, and that file passes the validation. (Although it's not a correct way to create the XML file, they have done it that way!)

So I want to know how does XmlReaderSettings work? And how to check that the XML file is not the XSD file?

Here is my code:

public static class XmlValidator
    {

        /// <summary>
        /// Basic Validation of DA application.
        /// Validate xml file with xsd file.
        /// : return list of errors from validation, return empty list if no error occur.
        /// </summary>
        /// <param name="pathXml">Xml file path.</param>
        /// <param name="pathXsd">Xsd file path.</param>
        /// <returns>Return list of errors from validation, return empty list if no error occur.</returns>
        public static List<string> Validate(string pathXml, string pathXsd, Action<DAStatus> callBack = null)
        {
            if (string.IsNullOrWhiteSpace(pathXml) || string.IsNullOrWhiteSpace(pathXsd))
            {
                throw new ArgumentException("Null or Empty are detected.");
            }
            else if (Path.GetExtension(pathXml).ToLower() != ".xml")
            {
                throw new InvalidFileTypeException(pathXml, ".xml");
            }
            else if (Path.GetExtension(pathXsd).ToLower() != ".xsd")
            {
                throw new InvalidFileTypeException(pathXsd, ".xsd");
            }

            List<string> errorList = new List<string>();
            using (var fileStream = File.OpenRead(pathXml))
            {
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.Schemas.Add(null, pathXsd);
                settings.ValidationType = ValidationType.Schema;
                settings.ValidationEventHandler += (sender, e) => XMLReaderValidateHandler(e, errorList);
                XmlReader xml = XmlReader.Create(fileStream, settings);

                long lastPosition = 0;
                long[] percent = { 0, 0 };
                DAStatus progress = new DAStatus();

                while (xml.Read())
                {
                    // read and validate xml by xsd.
                    // Add callBack
                    if (callBack != null)
                    {
                        lastPosition = fileStream.Position;
                        percent[1] = Math.Min(100, (100 * lastPosition / fileStream.Length));
                        if (percent[0] < percent[1])
                        {
                            percent[0] = percent[1];
                            progress.ProgressPercent = percent[0];
                            callBack(progress);
                        }
                    }
                }
            }

            return errorList;
        }

        private static void XMLReaderValidateHandler(ValidationEventArgs e, List<string> errorList)
        {
            errorList.Add(e.Message);
        }
    }

Update: I don't think my question is duplicate to the question that you guys refer because from my understanding that question is about automatically use the XSD file from the specific location to validate the XML, but my question is more like a user-error from creating the XML file in a wrong way. (Normally they should create the XML file in the right way but they want me to validate the XSD-XML file instead.)

The user has already sent me the example of their XML file created by changing the XSD file so I can provide the example.

Normally the XSD element looks like this:

<xs:element name="address" type="M_Address" />

And they change the element like this (Also change the file extension to .xml):

<xs:element name="test district" type="M_Address" />
Akethanut
  • 3
  • 2
  • 4
  • It's like the user use the XSD but change extension to XML. I will update the example later if the user give me that file. – Akethanut Nov 21 '19 at 13:16
  • The example of what the customer has created is not valid XML and will not parse. Element names cannot contain spaces. Your only recourse is to tell them not to do that. – Tom W Nov 25 '19 at 04:59
  • @TomW Thanks, but what if the name field that they change is like name="test". Does it pass my XSD validation? If it passes, how to prevent it? Does telling the user not to create the XML file by changing values in the XSD file directly is the only way? – Akethanut Nov 25 '19 at 05:10
  • I'm not sure I understand what you are asking. A schema with an element `` describes a document that looks like `
    `. You can't just "change the names" in a schema to get a valid document, that is not at all how XML works.
    – Tom W Nov 25 '19 at 06:31
  • And thinking about it, my feeling is that the "document" they create like this probably validates because it doesn't contain anything in the namespace described by the schema itself, because its structure is totally different to what a real document should be. – Tom W Nov 25 '19 at 07:04
  • From the example in the post, the user should create the XML file with `
    ` but they change the name 'address' in the XSD to their address value and save as a new XML file and validate that new XML file with my library and the original XSD. If I understand you correctly. you tell me that the XML file is valid because it doesn't match the structure of the schema so the only solution is to tell them not to do that. Is that correct? I'm sorry to make you confused.
    – Akethanut Nov 25 '19 at 08:03
  • Thanks for your help, I will talk to users to make them understand about this. – Akethanut Nov 25 '19 at 08:35

0 Answers0