How do I validate xml against a DTD file in Python

后端 未结 2 530
礼貌的吻别
礼貌的吻别 2020-12-02 13:45

I need to validate an XML string (and not a file) against a DTD description file.

How can that be done in python?

2条回答
  •  眼角桃花
    2020-12-02 13:53

    from the examples directory in the libxml2 python bindings:

    #!/usr/bin/python -u
    import libxml2
    import sys
    
    # Memory debug specific
    libxml2.debugMemory(1)
    
    dtd=""""""
    instance="""
    """
    
    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
    

提交回复
热议问题