2008-08-19 69 views

回答

29

另一個不錯的選擇是lxml's validation,我覺得這很好用。

從lxml的網站採取了一個簡單的例子:

from StringIO import StringIO 

from lxml import etree 

dtd = etree.DTD(StringIO("""<!ELEMENT foo EMPTY>""")) 
root = etree.XML("<foo/>") 
print(dtd.validate(root)) 
# True 

root = etree.XML("<foo>bar</foo>") 
print(dtd.validate(root)) 
# False 
print(dtd.error_log.filter_from_errors()) 
# <string>:1:0:ERROR:VALID:DTD_NOT_EMPTY: Element foo was declared EMPTY this one has content 
7

從libxml2的Python綁定的例子目錄:

#!/usr/bin/python -u 
import libxml2 
import sys 

# Memory debug specific 
libxml2.debugMemory(1) 

dtd="""<!ELEMENT foo EMPTY>""" 
instance="""<?xml version="1.0"?> 
<foo></foo>""" 

dtd = libxml2.parseDTD(None, 'test.dtd') 
ctxt = libxml2.newValidCtxt() 
doc = libxml2.parseDoc(instance) 
ret = doc.validateDtd(ctxt, dtd) 
if ret != 1: 
    print "error doing DTD validation" 
    sys.exit(1) 

doc.freeDoc() 
dtd.freeDtd() 
del dtd 
del ctxt 
+0

注意,libxml2的綁定不支持Python標準庫的一部分,即沒有內置。 – ChuckB 2008-11-07 15:42:28