簡體   English   中英

在C#中使用xsd驗證xml文件。它實際驗證多少?

[英]validate xml file using xsd in C#.. How much does it actually validate?

一直在嘗試為我的xml文件創建一個驗證器。 我使用了在此站點上可以找到的其他一些示例(例如, 如何驗證XML文檔? )。

我只是沒有看到它按我期望的方式工作。 實際驗證了什么?

幾乎無論我在xml文件中進行什么更改,驗證器劑量器都將其視為錯誤。 我以為驗證器將查看xml文件是否包含xsd中未定義的元素。 驗證器僅捕獲正常的xml語法錯誤。

那么,如果沒有影響,使用xsd有什么意義呢?

我的驗證人

string xsd_file = "Message.xsd";
XmlSchema xsd = new XmlSchema();
xsd.SourceUri = xsd_file;

XmlSchemaSet ss = new XmlSchemaSet();
ss.ValidationEventHandler += new ValidationEventHandler(ValidationEventHandler);
ss.Add(null, xsd_file);
if (ss.Count > 0)
{
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.ValidationType = ValidationType.Schema;
    settings.Schemas.Add(ss);
    settings.Schemas.Compile();
    settings.ValidationEventHandler += new ValidationEventHandler(ValidationEventHandler);
    XmlTextReader r = new XmlTextReader(filepath);
    using (XmlReader reader = XmlReader.Create(r, settings))
    {
        try
        {
            while (reader.Read())
            {
            }
        }
        catch (XmlException ex)
        {

            throw;
        }                        
    }
}

驗證事件處理程序的代碼丟失。

看我的工作代碼有一點不同我有這個

settings.ValidationFlags = XmlSchemaValidationFlags.ProcessInlineSchema | XmlSchemaValidationFlags.ReportValidationFlags;

忘記了為什么我必須添加它。

首先要做的是確保觸發了事件處理程序,之后這可能是xsd的問題。

暫無
暫無

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

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