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

后端 未结 3 868
無奈伤痛
無奈伤痛 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 03:03

    private static bool _isValid = true;
    static void Main(string[] args)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            using (FileStream file = new FileStream("C:\\MyFolder\\Product.dtd", FileMode.Open, FileAccess.Read))
            {
                byte[] bytes = new byte[file.Length];
                file.Read(bytes, 0, (int) file.Length);
                ms.Write(bytes, 0, (int) file.Length);
            }
            using (FileStream file = new FileStream("C:\\MyFolder\\Product.xml", FileMode.Open, FileAccess.Read))
            {
                byte[] bytes = new byte[file.Length];
                file.Read(bytes, 0, (int) file.Length);
                ms.Write(bytes, 0, (int) file.Length);
            }
            ms.Position = 0;
    
            var settings = new XmlReaderSettings();
            settings.DtdProcessing = DtdProcessing.Parse;
            settings.ValidationType = ValidationType.DTD;
            settings.ValidationEventHandler += new ValidationEventHandler(OnValidationEvent);
            var reader = XmlReader.Create(ms, settings);
    
            // Parse the file.  
            while (reader.Read()) ;
        }
        // Check whether the document is valid or invalid.
        if (_isValid)
            Console.WriteLine("Document is valid");
        else
            Console.WriteLine("Document is invalid");
    }
    
    private static void OnValidationEvent(object obj, ValidationEventArgs args)
    {
        _isValid = false;
        Console.WriteLine("Validation event\n" + args.Message);
    }
    

提交回复
热议问题