0

I am currently limited to using libxml2 (instead of lxml) for parsing on QNX 6.5. I want to validate my xml using a DTD loaded from a string, instead of from a file.

lxml lets you do this:

import lxml
from lxml import etree
from StringIO import StringIO

dtd_string = """
<!ELEMENT page (title)>
<!ELEMENT title (#PCDATA)>
"""

xml = """
<page>
  <title>Hello</title>
 </page>
 """

dtd = etree.DTD(StringIO(dtd_string))
root = etree.fromstring(xml)
is_valid = dtd.validate(root)

I would like to do the same using libxml2. I can load the DTD from file, but don't know and can't find the syntax to load it from string:

import libxml2
dtd = libxml2.parseDTD(None, dtd_file)  #How to parse DTD from a string??
ctxt = libxml2.newValidCtxt()
doc = libxml2.parseDoc(xml)
is_valid = doc.validateDtd(ctxt, dtd)
#cleanup omitted 

Does anyone happen to know how to do this in libxml2?

Ed Beaty
  • 415
  • 1
  • 6
  • 14

1 Answers1

0

Enh, I broke down and just read the xml to a string, and appended the dtd to it.

I'm still open to any better solutions.

import libxml2

doc = None
dtd = None
ctxt = None

try:

    xml = MY_DTD + filehandle.read().replace('\n', '') 

    ctxt = libxml2.newValidCtxt()

    doc = libxml2.parseDoc(xml)

    if not doc.validateDocument(ctxt):
        return 

    root = doc.children

    ...
Ed Beaty
  • 415
  • 1
  • 6
  • 14