簡體   English   中英

使用C#對帶有導入的XSD驗證XML

[英]Validate an XML against XSD with imports using C#

我需要針對一組XSD模式驗證XML文檔。 有一個頂級架構可以導入其他架構,嵌套架構也可以導入某些架構。 例如,模式a.xsd導入b.xsd和c.xsd; b.xsd導入d.xsd。 在此示例中,a.xsd是頂級架構。

我將以下代碼用於此類驗證:

static void Main(string[] args)
{
    try
    {
        var settings = new XmlReaderSettings();
        settings.ValidationType = ValidationType.Schema;
        settings.ConformanceLevel = ConformanceLevel.Document;
        settings.Schemas.Add("targetNs", "path/to/a.xsd");
        settings.ValidationEventHandler += ValidateHandler;

        var reader = XmlReader.Create("path/to/file.xml", settings);
        while (reader.Read()) ;
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

private static void ValidateHandler(object sender, ValidationEventArgs e)
{
    Console.WriteLine(e.Message);
}

盡管上面的代碼隱式地使用嵌套模式進行評估,但是存在一個問題:如果某些嵌套模式無效的XML文檔,則將其忽略而沒有任何異常。

您能幫我解決這個問題嗎?

如果需要在驗證文檔之前驗證架構,則可以執行以下操作:

try
{
    using (FileStream fs = File.OpenRead("path/to/a.xsd"))
    {
        XmlSchema schema = XmlSchema.Read(fs, ValidateHandler);
    }
}
catch (Exception e)
{
    throw new Exception("Schema file is invalid. " + e.Message);
}

然后,將架構添加到您的設置中,如下所示:

schema.TargetNamespace = "targetNs";
settings.Schemas.Addschema(schema);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM