title: Validating XML with an in-memory DTD in C using libxml2
body: <p>I need to validate XML using DTD stored in memory, i.e. something like the following: </p>
  
  <pre class="lang-c prettyprint-override"><code>static const char *dtd_str = "&lt;!ELEMENT ...&gt;";
  xmlDtdPtr dtd;
  
  dtd = xmlParseMemoryDtd(dtd_str);
  </code></pre>
  
  <p><code>XML_PARSE_DTDVALID</code> parser option allows to validate DTD embedded into XML:</p>
  
  <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;!DOCTYPE some_tag[
  &lt;!ELEMENT some_tag ...&gt;
  ...
  ]&gt;
  &lt;some_tag&gt;...&lt;/some_tag&gt;
  </code></pre>
  
  <p>So a workaround is to modify in-memory XML. Things become more complicated with
  a parser used in "push mode". In push mode we have to detect whether the XML
  declaration (<code>&lt;?xml ...?&gt;</code>), or start of the root element, then put our inline
  DTD between them.</p>
  
  <p>Could you suggest better solution?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>A workaround is to validate parsed XML posteriori as Daniel(_DV) suggested below.
  Example: <a href="http://bpaste.net/show/124241/" rel="nofollow">main.c</a>, <a href="http://bpaste.net/show/124243/" rel="nofollow">response.xml</a>.</p>
  
  <p>But I was searching for way to "embed" a DTD and validate XML "on-the-fly" while libxml2 parses XML chunk-by-chunk.
  The following aproach doesn't work for me:</p>
  
  <pre class="lang-c prettyprint-override"><code>xmlCtxtUseOptions(ctxt, XML_PARSE_NOENT | XML_PARSE_NOWARNING | XML_PARSE_DTDVALID);
  
  ctxt-&gt;sax-&gt;internalSubset = ngx_http_file_chunks_sax_internal_subset;
  ctxt-&gt;sax-&gt;externalSubset = NULL;
  </code></pre>
  
  <pre><code>$ ./parsexml 
  validity error : Validation failed: no DTD found !
  &lt;response&gt;
           ^
  Document is not valid
  </code></pre>