Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do i validate xml against dtd using python?

Tags:

python

xml

I have a xml file "sample.xml" as:

<?xml version="1.0" encoding="UTF8" ?>
< !DOCTYPE nodedescription SYSTEM "sample.dtd" >
<node_description>
    <target id="windows 32bit">
        <graphics>nvidia_970</graphics>
        <power_plug_type>energenie_eu</power_plug_type>
        <test>unit test</test>
   </target>
   <target id="windows 64bit">
       <graphics>nvidia_870</graphics>
       <power_plug_type>energenie_eu</power_plug_type>
       <test>performance test</test>
   </target>
</node_description>

and respective dtd as "sample.dtd":

<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT node_description (target)*>
<!ATTLIST target id CDATA #REQUIRED>
<!ELEMENT target (graphics, power_plug_type, test)>
<!ELEMENT graphics (#PCDATA)*>
<!ELEMENT power_plug_type (#PCDATA)*>
<!ELEMENT test (#PCDATA)*>

I want "sample.xml" to get validated against "sample.dtd" by making use of python script. How will i achieve this? kindly help.

like image 785
anamika email Avatar asked Aug 02 '15 07:08

anamika email


1 Answers

The lxml lib is well suited for this:

With sample.txt and sample.dtd in the current working directory, you can simply run:

from lxml import etree
parser = etree.XMLParser(dtd_validation=True)
tree = etree.parse("sample.xml", parser)

Results in:

XMLSyntaxError: root and DTD name do not match 'node_description' and 'nodedescription', line 3, column 18

See here for more detail. Also, a related question

like image 72
lemonhead Avatar answered Sep 29 '22 01:09

lemonhead