簡體   English   中英

使用XSD架構驗證XML,而無需使用C#更改XML

[英]Validate XML with a XSD Schema without changing the XML using C#

我有一個XML文件,但XML中沒有模式,因此需要針對XSD模式驗證XML。 我看到了很多示例,其中將XSD注入XML,然后驗證XML。 我不想更改XML,是否可以在不更改XML的情況下針對架構驗證XML?

用C#編寫幾行代碼很容易。

我創建了一個簡單的命令行界面實用程序,該實用程序具有兩個參數:XML,XSD並進行驗證。

您可以在這里下載。

這是主要代碼:

            // 1- Read XML file content
            reader = new XmlTextReader(XMLPath);

            // 2- Read Schema file content
            StreamReader SR = new StreamReader(XSDPath);

            // 3- Create a new instance of XmlSchema object
            XmlSchema Schema = new XmlSchema();
            // 4- Set Schema object by calling XmlSchema.Read() method
            Schema = XmlSchema.Read(SR,
                new ValidationEventHandler(ReaderSettings_ValidationEventHandler));

            // 5- Create a new instance of XmlReaderSettings object
            XmlReaderSettings ReaderSettings = new XmlReaderSettings();
            // 6- Set ValidationType for XmlReaderSettings object
            ReaderSettings.ValidationType = ValidationType.Schema;
            // 7- Add Schema to XmlReaderSettings Schemas collection
            ReaderSettings.Schemas.Add(Schema);

            // 8- Add your ValidationEventHandler address to
            // XmlReaderSettings ValidationEventHandler
            ReaderSettings.ValidationEventHandler +=
                new ValidationEventHandler(ReaderSettings_ValidationEventHandler);

            // 9- Create a new instance of XmlReader object
            XmlReader objXmlReader = XmlReader.Create(reader, ReaderSettings);


            // 10- Read XML content in a loop
            while (objXmlReader.Read())
            { /*Empty loop*/}

您可以將架構添加到xml文檔

doc.Schemas.Add(schema);

然后驗證一下

bool xmlvalid = true;
string lastXmlError = "";

doc.Validate(new System.Xml.Schema.ValidationEventHandler(
    delegate(object sender, System.Xml.Schema.ValidationEventArgs args)
    {
        if (args.Severity == System.Xml.Schema.XmlSeverityType.Error)
            {
                xmlvalid = false;
                lastXmlError = args.Message;
            }
    }));

if (!xmlvalid)
   //raise error

僅當您要繼續驗證文檔而不是第一個驗證錯誤時,才提供ValidationEventHandler。 否則,只需執行以下操作:

private bool ValidateDocument(string xmlFile, string xsdFile)
{
    XmlReaderSettings settings = new XmlReaderSettings{ValidationType 
      = ValidationType.Schema};
    settings.Schemas.Add(XmlSchema.Read(XmlReader.Create(xsdFile)));
    XmlReader reader = XmlReader.Create(xmlFile, settings);

    try
    {
        while(reader.Read());
        return true;
    }
    catch (XmlException ex) 
    {
        // XmlException indicates a validation error occurred.
        return false;
    }
}

以下鏈接提供了更多信息:

http://msdn.microsoft.com/en-us/library/1xe0740a.aspx

http://support.microsoft.com/kb/307379

暫無
暫無

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

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