.NET : How to validate XML file with DTD without DOCTYPE declaration

后端 未结 3 859
無奈伤痛
無奈伤痛 2021-01-12 02:12

I have an XML file with no DOCTYPE declaration that I would like to validate with an external DTD upon reading.

Dim x_set As Xml.XmlReaderSettings = New Xml.         


        
3条回答
  •  醉话见心
    2021-01-12 02:44

    I have used the following function successfully before, which should be easy to adapt. How ever this relies on creating a XmlDocument as magnifico mentioned. This can be achieved by:

    XmlDocument doc = new XmlDocument();
    doc.Load( filename );
    doc.InsertBefore( doc.CreateDocumentType( "doc_type_name", null, DtdFilePath, null ), 
        doc.DocumentElement );
    
    
    /// 
    /// Class to test a document against DTD
    /// 
    /// XML The document to validate
    private static bool ValidateDoc( XmlDocument doc )
    {
        bool isXmlValid = true;
        StringBuilder xmlValMsg = new StringBuilder();
    
        StringWriter sw = new StringWriter();
        doc.Save( sw );
        doc.Save( TestFilename );
    
        XmlReaderSettings settings = new XmlReaderSettings();
        settings.ProhibitDtd = false;
        settings.ValidationType = ValidationType.DTD;
        settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;
        settings.ValidationEventHandler += new ValidationEventHandler( delegate( object sender, ValidationEventArgs args )
        {
            isXmlValid = false;
            xmlValMsg.AppendLine( args.Message );
        } );
    
        XmlReader validator = XmlReader.Create( new StringReader( sw.ToString() ), settings );
    
        while( validator.Read() )
        {
        }
        validator.Close();
    
        string message = xmlValMsg.ToString();
        return isXmlValid;
    }
    

提交回复
热议问题