user3033490
user3033490

Reputation:

Obtain name of DTD file using XmlReader

Parsing an XML file with XmlReader, how can I get the details of the DOCTYPE declaration, especially the filename?

Given the lines below, I'd like to get the information "sample", "SYSTEM" and "sample.dtd".

<?xml version="1.0"?>
<!DOCTYPE sample SYSTEM "sample.dtd">
<sample>
</sample>

That would give me root element name "sample":

if (reader.NodeType == XmlNodeType.DocumentType)
    Console.WriteLine(reader.Name);
}

Upvotes: 2

Views: 347

Answers (1)

pfx
pfx

Reputation: 23314

The DTD can be read as an attribute named SYSTEM.

var dtd = reader.GetAttribute("SYSTEM");

Full example:

var pathToXmlFile = @"c:\folder\file.xml";
using (XmlReader reader = XmlReader.Create(  
    pathToXmlFile, 
    new XmlReaderSettings { DtdProcessing = DtdProcessing.Parse }
    ))
{
    while (reader.Read())
    {
        if (reader.NodeType == XmlNodeType.DocumentType)
        {
            var dtd = reader.GetAttribute("SYSTEM"); // sample.dtd
        }
     }
 }

Upvotes: 0

Related Questions