C# read XML with DTD verification -
i'm trying read xml file dtd verification no mather how seems program doesn't read dtd file. have concentrated problem small xml file , small dtd file:
test.xml - located @ c:\test.xml
<?xml version="1.0"?> <!doctype product system "test.dtd"> <product productid="123"> <productname>rugby jersey</productname> </product>
test.dtd - located @ c:\test.dtd
<!element product (productname)> <!attlist product productid cdata #required> <!element productname (#pcdata)>
my c# program looks this
namespace xml_to_csv_converter { public partial class form1 : form { public form1() { initializecomponent(); } private void form1_load(object sender, eventargs e) { readxmlwithdtd(); } public void readxmlwithdtd() { // set validation settings. xmlreadersettings settings = new xmlreadersettings(); settings.validationtype = validationtype.dtd; settings.dtdprocessing = dtdprocessing.parse; settings.validationeventhandler += new validationeventhandler(validationcallback); settings.ignorewhitespace = true; // create xmlreader object. xmlreader reader = xmlreader.create("c:/test.xml", settings); // parse file. while (reader.read()) { system.console.writeline("{0}, {1}: {2} ", reader.nodetype, reader.name, reader.value); } } private static void validationcallback(object sender, validationeventargs e) { if (e.severity == xmlseveritytype.warning) console.writeline("warning: matching schema not found. no validation occurred." + e.message); else // error console.writeline("validation error: " + e.message); } } }
this results in output:
xmldeclaration, xml: version="1.0" documenttype, product: validation error: 'product' element not declared. element, product: validation error: 'productname' element not declared. element, productname: text, : rugby jersey endelement, productname: endelement, product:
i have tried have files in defferent locations , have tried both relative , absolute paths. have tried copy example microsoft webpage , resulted in same problem. have idea of can problem? there way see if program able load dtd file?
you need add resolver.
xmlreadersettings settings = new xmlreadersettings(); // set resolver settings.xmlresolver = new xmlurlresolver(); settings.validationtype = validationtype.dtd; settings.dtdprocessing = dtdprocessing.parse; settings.validationeventhandler += new validationeventhandler(validationcallback); settings.ignorewhitespace = true;
as long 2 files in same directory, work. alternatively need provide url dtd.
xmlurlresolver
can overridden provide additional semantics resolution process.
Comments
Post a Comment