Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

xml

vb.net

dtd

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?

like image 379
Vincent Avatar asked Jan 22 '09 18:01

Vincent


2 Answers

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;
}
like image 172
bstoney Avatar answered Oct 04 '22 02:10

bstoney


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?

like image 38
Jim Counts Avatar answered Oct 04 '22 02:10

Jim Counts