1

そのため、XmlSchemaSet を使用して xsd ファイルに対して xml ファイルを検証しようとしています。プロジェクトに次のソリューションを実装しようとしましたが、xml ファイル内のすべてのエラーが見つかりましたが、取得する行番号は何らかの理由で常に 1 です。この問題に対処するコードは次のとおりです。

xmlValidate クラス:

public class xmlValidate
{
    private IList<string> allValidationErrors = new List<string>();

    public IList<string> AllValidationErrors
    {
        get
        {
            return this.allValidationErrors;
        }
    }

    public void checkForErrors(object sender, ValidationEventArgs error)
    {
        if (error.Severity == XmlSeverityType.Error || error.Severity == XmlSeverityType.Warning)
        {
            this.allValidationErrors.Add(String.Format("<br/>" + "Line: {0}: {1}", error.Exception.LineNumber, error.Exception.Message));
        }
    }
}

主な機能:

public string validate(string xmlUrl, string xsdUrl)
    {
        XmlDocument xml = new XmlDocument();
        xml.Load(xmlUrl);
        xml.Schemas.Add(null, xsdUrl);

        string xmlString = xml.OuterXml;
        XmlSchemaSet xmlSchema = new XmlSchemaSet();
        xmlSchema.Add(null, xsdUrl); 

        if (xmlSchema == null)
        {
            return "No Schema found at the given url."; 
        }

        string errors = "";
        xmlValidate handler = new xmlValidate();
        XmlReaderSettings settings = new XmlReaderSettings();
        settings.CloseInput = true;
        settings.ValidationType = ValidationType.Schema;
        settings.ValidationEventHandler += new ValidationEventHandler(handler.checkForErrors);
        settings.Schemas.Add(xmlSchema);
        settings.ValidationFlags = XmlSchemaValidationFlags.ProcessInlineSchema 
                                 | XmlSchemaValidationFlags.ProcessSchemaLocation 
                                 | XmlSchemaValidationFlags.ReportValidationWarnings 
                                 | XmlSchemaValidationFlags.ProcessIdentityConstraints;
        StringReader sr = new StringReader(xmlString); 

        using (XmlReader vr = XmlReader.Create(sr, settings))
        {
            while (vr.Read()) { }
        }

        if (handler.AllValidationErrors.Count > 0)
        {
            foreach (String errorMessage in handler.AllValidationErrors)
            {
                errors += errorMessage; 
            }
            return errors; 
        }

        return "No Errors!"; 
   }

誰かが私の問題を見ていますか? 前もって感謝します!

4

1 に答える 1