Validating XML on XSD with the error line numbers

前端 未结 6 1071
盖世英雄少女心
盖世英雄少女心 2021-01-04 15:19

Is there any way to validate an XML file on an XSD schema with the output of the error line numbers?

The XmlReader reader doesn\'t allow line numbers, it shows only

6条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-04 16:00

    Try this working example. IXmlLineInfo gets you the line info. I am getting all the list of errors here, concatenating the Line number, unique id of that specific record, the element name where the error occurred and adding it to a list.

           //get the input file here - You can replace this to your local file
            var httpRequest = HttpContext.Current.Request;
    
            if (httpRequest.Files.Count > 0)
            {
                var postedFile = httpRequest.Files[0];
    
                //sete the xsd schema path                    
                string xsdPath = HttpContext.Current.Server.MapPath("~/XSD/MyFile.xsd");
    
                //set the XSD schema here
                var schema = new XmlSchemaSet();
                schema.Add("", xsdPath);
                var Message = "";
    
                //validate the xml schema here
                XDocument document = XDocument.Load(postedFile.InputStream, LoadOptions.PreserveWhitespace | LoadOptions.SetLineInfo | LoadOptions.SetBaseUri);
                //create a lists to add the error records
                List lstErrors = new List();
                document.Validate(schema, ValidationEventHandler);
    
                //validate all the errors
                document.Validate(schema, (sender, args) =>
                 {
                     IXmlLineInfo item = sender as IXmlLineInfo;
                     if (item != null && item.HasLineInfo())
                     {
                         //capture all the details needed here seperated by colons
                         Message = item.LineNumber + ";" +
                         (((System.Xml.Linq.XObject)item).Parent.Element("id")).Value + ";" +
                         ((System.Xml.Linq.XElement)item).Name.LocalName + ";" +
                         args.Message + Environment.NewLine;
                         //add the error to a list
                         lstErrors.Add(Message);
                     }
                 });
            }
    

提交回复
热议问题