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

12,725

Solution 1

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 );


/// <summary>
/// Class to test a document against DTD
/// </summary>
/// <param name="doc">XML The document to validate</param>
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;
}

Solution 2

Could you create an Xml.XmlDocument with the DTD you want, then append the XML file data to the in-memory Xml.XmlDocument, then validate that?

Share:
12,725

Related videos on Youtube

Vincent
Author by

Vincent

Updated on April 19, 2022

Comments

  • Vincent
    Vincent about 2 years

    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.XmlReaderSettings()
    x_set.XmlResolver = Nothing
    x_set.CheckCharacters = False
    x_set.ProhibitDtd = False
    x = XmlTextReader.Create(sChemin, x_set)
    

    How do you set the path for that external DTD? How do you validate?

  • CindyH
    CindyH over 12 years
    I'd vote this up 20 times if I could. I've gotten SOOO close but this did it. Thanks!
  • artragis
    artragis almost 10 years
    Really useful answer. For those who read this, the most recent version of .NET framework prefers settings.DtdProcessing = DtdProcessing.Parse instead of settings.ProhibidDtd = false.
  • AbcAeffchen
    AbcAeffchen over 9 years
    Your answer should contain an explanation of your code and a description how it solves the problem.
  • Matt
    Matt over 9 years
    I could not find a way for xml to be validated against an external DTD document. In my case, I'm receiving XML from a tcp/ip socket and I want to validate this against a DTD file. The above example shows how you can combine a DTD and some XML together in the same stream before using the the XmlReader object to do the DTD validation.
  • Harvey Lin
    Harvey Lin almost 7 years
    So, the solution is still that we have to add the DOCTYPE string at the beginning? Is there a way for the code to point to an external location not specified in the DOCTYPE string?
  • Johan Boulé
    Johan Boulé over 5 years
    That "ProhibitDtd" is a nasty bomb that only MS could have invented. A more honest naming for this setting would have been LetsGetRidAllAllStandardComplianceSoAsToMakeYourLifeMiserabl‌​e, which length and expressiveness is on par with .NET's style.