Sophie

Sophie

distrib > CentOS > 5 > i386 > by-pkgid > 90dba77ca23efa667b541b5c0dd77497 > files > 395

python-lxml-2.0.11-2.el5.i386.rpm

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Docutils 0.4.1: http://docutils.sourceforge.net/" />
<title>Validation with lxml</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div class="document" id="validation-with-lxml">
<div class="sidemenu"><ul id="lxml"><li><span class="section title">lxml</span><ul class="menu foreign" id="index"><li class="menu title"><a href="index.html">lxml</a><ul class="submenu"><li class="menu item"><a href="index.html#introduction">Introduction</a></li><li class="menu item"><a href="index.html#documentation">Documentation</a></li><li class="menu item"><a href="index.html#download">Download</a></li><li class="menu item"><a href="index.html#mailing-list">Mailing list</a></li><li class="menu item"><a href="index.html#bug-tracker">Bug tracker</a></li><li class="menu item"><a href="index.html#license">License</a></li><li class="menu item"><a href="index.html#old-versions">Old Versions</a></li></ul></li></ul><ul class="menu foreign" id="intro"><li class="menu title"><a href="intro.html">Why lxml?</a><ul class="submenu"><li class="menu item"><a href="intro.html#motto">Motto</a></li><li class="menu item"><a href="intro.html#aims">Aims</a></li></ul></li></ul><ul class="menu foreign" id="installation"><li class="menu title"><a href="installation.html">Installing lxml</a><ul class="submenu"><li class="menu item"><a href="installation.html#requirements">Requirements</a></li><li class="menu item"><a href="installation.html#installation">Installation</a></li><li class="menu item"><a href="installation.html#building-lxml-from-sources">Building lxml from sources</a></li><li class="menu item"><a href="installation.html#ms-windows">MS Windows</a></li><li class="menu item"><a href="installation.html#macos-x">MacOS-X</a></li></ul></li></ul><ul class="menu foreign" id="lxml2"><li class="menu title"><a href="lxml2.html">What's new in lxml 2.0?</a><ul class="submenu"><li class="menu item"><a href="lxml2.html#changes-in-etree-and-objectify">Changes in etree and objectify</a></li><li class="menu item"><a href="lxml2.html#new-modules">New modules</a></li></ul></li></ul><ul class="menu foreign" id="performance"><li class="menu title"><a href="performance.html">Benchmarks and Speed</a><ul class="submenu"><li class="menu item"><a href="performance.html#general-notes">General notes</a></li><li class="menu item"><a href="performance.html#how-to-read-the-timings">How to read the timings</a></li><li class="menu item"><a href="performance.html#parsing-and-serialising">Parsing and Serialising</a></li><li class="menu item"><a href="performance.html#the-elementtree-api">The ElementTree API</a></li><li class="menu item"><a href="performance.html#xpath">XPath</a></li><li class="menu item"><a href="performance.html#a-longer-example">A longer example</a></li><li class="menu item"><a href="performance.html#lxml-objectify">lxml.objectify</a></li></ul></li></ul><ul class="menu foreign" id="compatibility"><li class="menu title"><a href="compatibility.html">ElementTree compatibility of lxml.etree</a></li></ul><ul class="menu foreign" id="FAQ"><li class="menu title"><a href="FAQ.html">lxml FAQ - Frequently Asked Questions</a><ul class="submenu"><li class="menu item"><a href="FAQ.html#general-questions">General Questions</a></li><li class="menu item"><a href="FAQ.html#installation">Installation</a></li><li class="menu item"><a href="FAQ.html#contributing">Contributing</a></li><li class="menu item"><a href="FAQ.html#bugs">Bugs</a></li><li class="menu item"><a href="FAQ.html#threading">Threading</a></li><li class="menu item"><a href="FAQ.html#parsing-and-serialisation">Parsing and Serialisation</a></li><li class="menu item"><a href="FAQ.html#xpath-and-document-traversal">XPath and Document Traversal</a></li></ul></li></ul></li></ul><ul id="Developing with lxml"><li><span class="section title">Developing with lxml</span><ul class="menu foreign" id="tutorial"><li class="menu title"><a href="tutorial.html">The lxml.etree Tutorial</a><ul class="submenu"><li class="menu item"><a href="tutorial.html#the-element-class">The Element class</a></li><li class="menu item"><a href="tutorial.html#the-elementtree-class">The ElementTree class</a></li><li class="menu item"><a href="tutorial.html#parsing-from-strings-and-files">Parsing from strings and files</a></li><li class="menu item"><a href="tutorial.html#namespaces">Namespaces</a></li><li class="menu item"><a href="tutorial.html#the-e-factory">The E-factory</a></li><li class="menu item"><a href="tutorial.html#elementpath">ElementPath</a></li></ul></li></ul><ul class="menu foreign" id="api index"><li class="menu title"><a href="api/index.html">API reference</a></li></ul><ul class="menu foreign" id="api"><li class="menu title"><a href="api.html">APIs specific to lxml.etree</a><ul class="submenu"><li class="menu item"><a href="api.html#lxml-etree">lxml.etree</a></li><li class="menu item"><a href="api.html#other-element-apis">Other Element APIs</a></li><li class="menu item"><a href="api.html#trees-and-documents">Trees and Documents</a></li><li class="menu item"><a href="api.html#iteration">Iteration</a></li><li class="menu item"><a href="api.html#error-handling-on-exceptions">Error handling on exceptions</a></li><li class="menu item"><a href="api.html#error-logging">Error logging</a></li><li class="menu item"><a href="api.html#serialisation">Serialisation</a></li><li class="menu item"><a href="api.html#xinclude-and-elementinclude">XInclude and ElementInclude</a></li><li class="menu item"><a href="api.html#write-c14n-on-elementtree">write_c14n on ElementTree</a></li></ul></li></ul><ul class="menu foreign" id="parsing"><li class="menu title"><a href="parsing.html">Parsing XML and HTML with lxml</a><ul class="submenu"><li class="menu item"><a href="parsing.html#parsers">Parsers</a></li><li class="menu item"><a href="parsing.html#the-target-parser-interface">The target parser interface</a></li><li class="menu item"><a href="parsing.html#the-feed-parser-interface">The feed parser interface</a></li><li class="menu item"><a href="parsing.html#iterparse-and-iterwalk">iterparse and iterwalk</a></li><li class="menu item"><a href="parsing.html#python-unicode-strings">Python unicode strings</a></li></ul></li></ul><ul class="menu current" id="validation"><li class="menu title"><a href="validation.html">Validation with lxml</a><ul class="submenu"><li class="menu item"><a href="validation.html#validation-at-parse-time">Validation at parse time</a></li><li class="menu item"><a href="validation.html#dtd">DTD</a></li><li class="menu item"><a href="validation.html#relaxng">RelaxNG</a></li><li class="menu item"><a href="validation.html#xmlschema">XMLSchema</a></li><li class="menu item"><a href="validation.html#schematron">Schematron</a></li></ul></li></ul><ul class="menu foreign" id="xpathxslt"><li class="menu title"><a href="xpathxslt.html">XPath and XSLT with lxml</a><ul class="submenu"><li class="menu item"><a href="xpathxslt.html#xpath">XPath</a></li><li class="menu item"><a href="xpathxslt.html#xslt">XSLT</a></li></ul></li></ul><ul class="menu foreign" id="objectify"><li class="menu title"><a href="objectify.html">lxml.objectify</a><ul class="submenu"><li class="menu item"><a href="objectify.html#the-lxml-objectify-api">The lxml.objectify API</a></li><li class="menu item"><a href="objectify.html#asserting-a-schema">Asserting a Schema</a></li><li class="menu item"><a href="objectify.html#objectpath">ObjectPath</a></li><li class="menu item"><a href="objectify.html#python-data-types">Python data types</a></li><li class="menu item"><a href="objectify.html#how-data-types-are-matched">How data types are matched</a></li><li class="menu item"><a href="objectify.html#what-is-different-from-lxml-etree?">What is different from lxml.etree?</a></li></ul></li></ul><ul class="menu foreign" id="lxmlhtml"><li class="menu title"><a href="lxmlhtml.html">lxml.html</a><ul class="submenu"><li class="menu item"><a href="lxmlhtml.html#parsing-html">Parsing HTML</a></li><li class="menu item"><a href="lxmlhtml.html#html-element-methods">HTML Element Methods</a></li><li class="menu item"><a href="lxmlhtml.html#running-html-doctests">Running HTML doctests</a></li><li class="menu item"><a href="lxmlhtml.html#creating-html-with-the-e-factory">Creating HTML with the E-factory</a></li><li class="menu item"><a href="lxmlhtml.html#working-with-links">Working with links</a></li><li class="menu item"><a href="lxmlhtml.html#forms">Forms</a></li><li class="menu item"><a href="lxmlhtml.html#cleaning-up-html">Cleaning up HTML</a></li><li class="menu item"><a href="lxmlhtml.html#html-diff">HTML Diff</a></li><li class="menu item"><a href="lxmlhtml.html#examples">Examples</a></li></ul></li></ul><ul class="menu foreign" id="cssselect"><li class="menu title"><a href="cssselect.html">lxml.cssselect</a><ul class="submenu"><li class="menu item"><a href="cssselect.html#the-cssselector-class">The CSSSelector class</a></li><li class="menu item"><a href="cssselect.html#css-selectors">CSS Selectors</a></li><li class="menu item"><a href="cssselect.html#limitations">Limitations</a></li></ul></li></ul><ul class="menu foreign" id="elementsoup"><li class="menu title"><a href="elementsoup.html">BeautifulSoup Parser</a><ul class="submenu"><li class="menu item"><a href="elementsoup.html#entity-handling">Entity handling</a></li><li class="menu item"><a href="elementsoup.html#using-soupparser-as-a-fallback">Using soupparser as a fallback</a></li></ul></li></ul></li></ul><ul id="Extending lxml"><li><span class="section title">Extending lxml</span><ul class="menu foreign" id="resolvers"><li class="menu title"><a href="resolvers.html">Document loading and URL resolving</a><ul class="submenu"><li class="menu item"><a href="resolvers.html#resolvers">Resolvers</a></li><li class="menu item"><a href="resolvers.html#document-loading-in-context">Document loading in context</a></li><li class="menu item"><a href="resolvers.html#i-o-access-control-in-xslt">I/O access control in XSLT</a></li></ul></li></ul><ul class="menu foreign" id="extensions"><li class="menu title"><a href="extensions.html">Extension functions for XPath and XSLT</a><ul class="submenu"><li class="menu item"><a href="extensions.html#the-functionnamespace">The FunctionNamespace</a></li><li class="menu item"><a href="extensions.html#global-prefix-assignment">Global prefix assignment</a></li><li class="menu item"><a href="extensions.html#the-xpath-context">The XPath context</a></li><li class="menu item"><a href="extensions.html#evaluators-and-xslt">Evaluators and XSLT</a></li><li class="menu item"><a href="extensions.html#evaluator-local-extensions">Evaluator-local extensions</a></li><li class="menu item"><a href="extensions.html#what-to-return-from-a-function">What to return from a function</a></li></ul></li></ul><ul class="menu foreign" id="element classes"><li class="menu title"><a href="element_classes.html">Using custom Element classes in lxml</a><ul class="submenu"><li class="menu item"><a href="element_classes.html#element-initialization">Element initialization</a></li><li class="menu item"><a href="element_classes.html#setting-up-a-class-lookup-scheme">Setting up a class lookup scheme</a></li><li class="menu item"><a href="element_classes.html#implementing-namespaces">Implementing namespaces</a></li></ul></li></ul><ul class="menu foreign" id="sax"><li class="menu title"><a href="sax.html">Sax support</a><ul class="submenu"><li class="menu item"><a href="sax.html#building-a-tree-from-sax-events">Building a tree from SAX events</a></li><li class="menu item"><a href="sax.html#producing-sax-events-from-an-elementtree-or-element">Producing SAX events from an ElementTree or Element</a></li><li class="menu item"><a href="sax.html#interfacing-with-pulldom-minidom">Interfacing with pulldom/minidom</a></li></ul></li></ul><ul class="menu foreign" id="capi"><li class="menu title"><a href="capi.html">The public C-API of lxml.etree</a><ul class="submenu"><li class="menu item"><a href="capi.html#writing-external-modules-in-cython">Writing external modules in Cython</a></li><li class="menu item"><a href="capi.html#writing-external-modules-in-c">Writing external modules in C</a></li></ul></li></ul></li></ul><ul id="Developing lxml"><li><span class="section title">Developing lxml</span><ul class="menu foreign" id="build"><li class="menu title"><a href="build.html">How to build lxml from source</a><ul class="submenu"><li class="menu item"><a href="build.html#cython">Cython</a></li><li class="menu item"><a href="build.html#subversion">Subversion</a></li><li class="menu item"><a href="build.html#setuptools">Setuptools</a></li><li class="menu item"><a href="build.html#running-the-tests-and-reporting-errors">Running the tests and reporting errors</a></li><li class="menu item"><a href="build.html#contributing-an-egg">Contributing an egg</a></li><li class="menu item"><a href="build.html#providing-newer-library-versions-on-mac-os-x">Providing newer library versions on Mac-OS X</a></li><li class="menu item"><a href="build.html#static-linking-on-windows">Static linking on Windows</a></li><li class="menu item"><a href="build.html#building-debian-packages-from-svn-sources">Building Debian packages from SVN sources</a></li></ul></li></ul><ul class="menu foreign" id="lxml source howto"><li class="menu title"><a href="lxml-source-howto.html">How to read the source of lxml</a><ul class="submenu"><li class="menu item"><a href="lxml-source-howto.html#what-is-cython?">What is Cython?</a></li><li class="menu item"><a href="lxml-source-howto.html#where-to-start?">Where to start?</a></li><li class="menu item"><a href="lxml-source-howto.html#lxml-etree">lxml.etree</a></li><li class="menu item"><a href="lxml-source-howto.html#python-modules">Python modules</a></li><li class="menu item"><a href="lxml-source-howto.html#lxml-objectify">lxml.objectify</a></li><li class="menu item"><a href="lxml-source-howto.html#lxml-pyclasslookup">lxml.pyclasslookup</a></li><li class="menu item"><a href="lxml-source-howto.html#lxml-html">lxml.html</a></li></ul></li></ul><ul class="menu foreign" id="changes 2 0 11"><li class="menu title"><a href="changes-2.0.11.html">Release Changelog</a></li></ul><ul class="menu foreign" id="credits"><li class="menu title"><a href="credits.html">Credits</a><ul class="submenu"><li class="menu item"><a href="credits.html#special-thanks-goes-to:">Special thanks goes to:</a></li></ul></li></ul></li></ul></div><h1 class="title">Validation with lxml</h1>
<p>Apart from the built-in DTD support in parsers, lxml currently supports three
schema languages: <a class="reference" href="http://en.wikipedia.org/wiki/Document_Type_Definition">DTD</a>, <a class="reference" href="http://www.relaxng.org/">Relax NG</a> and <a class="reference" href="http://www.w3.org/XML/Schema">XML Schema</a>.  All three provide
identical APIs in lxml, represented by validator classes with the obvious
names.</p>
<p>There is also initial support for <a class="reference" href="http://www.ascc.net/xml/schematron">Schematron</a>.  However, it does not currently
support error reporting in the validation phase due to insufficiencies in the
implementation as of libxml2 2.6.30.</p>
<div class="contents topic">
<p class="topic-title first"><a id="contents" name="contents">Contents</a></p>
<ul class="simple">
<li><a class="reference" href="#validation-at-parse-time" id="id3" name="id3">Validation at parse time</a></li>
<li><a class="reference" href="#id1" id="id4" name="id4">DTD</a></li>
<li><a class="reference" href="#relaxng" id="id5" name="id5">RelaxNG</a></li>
<li><a class="reference" href="#xmlschema" id="id6" name="id6">XMLSchema</a></li>
<li><a class="reference" href="#id2" id="id7" name="id7">Schematron</a></li>
</ul>
</div>
<p>The usual setup procedure:</p>
<pre class="literal-block">
&gt;&gt;&gt; from lxml import etree
&gt;&gt;&gt; from StringIO import StringIO
</pre>
<div class="section">
<h1><a id="validation-at-parse-time" name="validation-at-parse-time">Validation at parse time</a></h1>
<p>The parser in lxml can do on-the-fly validation of a document against
a DTD or an XML schema.  The DTD is retrieved automatically based on
the DOCTYPE of the parsed document.  All you have to do is use a
parser that has DTD validation enabled:</p>
<pre class="literal-block">
&gt;&gt;&gt; parser = etree.XMLParser(dtd_validation=True)
</pre>
<p>Obviously, a request for validation enables the DTD loading feature.
There are two other options that enable loading the DTD, but that do
not perform any validation.  The first is the <tt class="docutils literal"><span class="pre">load_dtd</span></tt> keyword
option, which simply loads the DTD into the parser and makes it
available to the document as external subset.  You can retrieve the
DTD from the parsed document using the <tt class="docutils literal"><span class="pre">docinfo</span></tt> property of the
result ElementTree object.  The internal subset is available as
<tt class="docutils literal"><span class="pre">internalDTD</span></tt>, the external subset is provided as <tt class="docutils literal"><span class="pre">externalDTD</span></tt>.</p>
<p>The third way way to activate DTD loading is with the
<tt class="docutils literal"><span class="pre">attribute_defaults</span></tt> option, which loads the DTD and weaves
attribute default values into the document.  Again, no validation is
performed unless explicitly requested.</p>
<p>XML schema is supported in a similar way, but requires an explicit
schema to be provided:</p>
<pre class="literal-block">
&gt;&gt;&gt; schema_root = etree.XML('''\
...   &lt;xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
...     &lt;xsd:element name="a" type="xsd:integer"/&gt;
...   &lt;/xsd:schema&gt;
... ''')
&gt;&gt;&gt; schema = etree.XMLSchema(schema_root)

&gt;&gt;&gt; parser = etree.XMLParser(schema = schema)
&gt;&gt;&gt; root = etree.fromstring("&lt;a&gt;5&lt;/a&gt;", parser)
</pre>
<p>If the validation fails (be it for a DTD or an XML schema), the parser
will raise an exception:</p>
<pre class="literal-block">
&gt;&gt;&gt; root = etree.fromstring("&lt;a&gt;no int&lt;/a&gt;", parser)
Traceback (most recent call last):
XMLSyntaxError: Element 'a': 'no int' is not a valid value of the atomic type 'xs:integer'.
</pre>
<p>If you want the parser to succeed regardless of the outcome of the
validation, you should use a non validating parser and run the
validation separately after parsing the document.</p>
</div>
<div class="section">
<h1><a id="id1" name="id1">DTD</a></h1>
<p>As described above, the parser support for DTDs depends on internal or
external subsets of the XML file.  This means that the XML file itself
must either contain a DTD or must reference a DTD to make this work.
If you want to validate an XML document against a DTD that is not
referenced by the document itself, you can use the <tt class="docutils literal"><span class="pre">DTD</span></tt> class.</p>
<p>To use the <tt class="docutils literal"><span class="pre">DTD</span></tt> class, you must first pass a filename or file-like object
into the constructor to parse a DTD:</p>
<pre class="literal-block">
&gt;&gt;&gt; f = StringIO("&lt;!ELEMENT b EMPTY&gt;")
&gt;&gt;&gt; dtd = etree.DTD(f)
</pre>
<p>Now you can use it to validate documents:</p>
<pre class="literal-block">
&gt;&gt;&gt; root = etree.XML("&lt;b/&gt;")
&gt;&gt;&gt; print dtd.validate(root)
True

&gt;&gt;&gt; root = etree.XML("&lt;b&gt;&lt;a/&gt;&lt;/b&gt;")
&gt;&gt;&gt; print dtd.validate(root)
False
</pre>
<p>The reason for the validation failure can be found in the error log:</p>
<pre class="literal-block">
&gt;&gt;&gt; print dtd.error_log.filter_from_errors()[0]
&lt;string&gt;:1:0:ERROR:VALID:DTD_NOT_EMPTY: Element b was declared EMPTY this one has content
</pre>
<p>As an alternative to parsing from a file, you can use the
<tt class="docutils literal"><span class="pre">external_id</span></tt> keyword argument to parse from a catalog.  The
following example reads the DocBook DTD in version 4.2, if available
in the system catalog:</p>
<pre class="literal-block">
dtd = etree.DTD(external_id = "-//OASIS//DTD DocBook XML V4.2//EN")
</pre>
</div>
<div class="section">
<h1><a id="relaxng" name="relaxng">RelaxNG</a></h1>
<p>The <tt class="docutils literal"><span class="pre">RelaxNG</span></tt> class takes an ElementTree object to construct a Relax NG
validator:</p>
<pre class="literal-block">
&gt;&gt;&gt; f = StringIO('''\
... &lt;element name="a" xmlns="http://relaxng.org/ns/structure/1.0"&gt;
...  &lt;zeroOrMore&gt;
...     &lt;element name="b"&gt;
...       &lt;text /&gt;
...     &lt;/element&gt;
...  &lt;/zeroOrMore&gt;
... &lt;/element&gt;
... ''')
&gt;&gt;&gt; relaxng_doc = etree.parse(f)
&gt;&gt;&gt; relaxng = etree.RelaxNG(relaxng_doc)
</pre>
<p>Alternatively, pass a filename to the <tt class="docutils literal"><span class="pre">file</span></tt> keyword argument to parse from
a file.  This also enables correct handling of include files from within the
RelaxNG parser.</p>
<p>You can then validate some ElementTree document against the schema. You'll get
back True if the document is valid against the Relax NG schema, and False if
not:</p>
<pre class="literal-block">
&gt;&gt;&gt; valid = StringIO('&lt;a&gt;&lt;b&gt;&lt;/b&gt;&lt;/a&gt;')
&gt;&gt;&gt; doc = etree.parse(valid)
&gt;&gt;&gt; relaxng.validate(doc)
True

&gt;&gt;&gt; invalid = StringIO('&lt;a&gt;&lt;c&gt;&lt;/c&gt;&lt;/a&gt;')
&gt;&gt;&gt; doc2 = etree.parse(invalid)
&gt;&gt;&gt; relaxng.validate(doc2)
False
</pre>
<p>Calling the schema object has the same effect as calling its validate
method. This is sometimes used in conditional statements:</p>
<pre class="literal-block">
&gt;&gt;&gt; invalid = StringIO('&lt;a&gt;&lt;c&gt;&lt;/c&gt;&lt;/a&gt;')
&gt;&gt;&gt; doc2 = etree.parse(invalid)
&gt;&gt;&gt; if not relaxng(doc2):
...     print "invalid!"
invalid!
</pre>
<p>If you prefer getting an exception when validating, you can use the
<tt class="docutils literal"><span class="pre">assert_</span></tt> or <tt class="docutils literal"><span class="pre">assertValid</span></tt> methods:</p>
<pre class="literal-block">
&gt;&gt;&gt; relaxng.assertValid(doc2)
Traceback (most recent call last):
  [...]
DocumentInvalid: Did not expect element c there, line 1

&gt;&gt;&gt; relaxng.assert_(doc2)
Traceback (most recent call last):
  [...]
AssertionError: Did not expect element c there, line 1
</pre>
<p>If you want to find out why the validation failed in the second case, you can
look up the error log of the validation process and check it for relevant
messages:</p>
<pre class="literal-block">
&gt;&gt;&gt; log = relaxng.error_log
&gt;&gt;&gt; print log.last_error
&lt;string&gt;:1:0:ERROR:RELAXNGV:RELAXNG_ERR_ELEMWRONG: Did not expect element c there
</pre>
<p>You can see that the error (ERROR) happened during RelaxNG validation
(RELAXNGV).  The message then tells you what went wrong.  You can also
look at the error domain and its type directly:</p>
<pre class="literal-block">
&gt;&gt;&gt; error = log.last_error
&gt;&gt;&gt; print error.domain_name
RELAXNGV
&gt;&gt;&gt; print error.type_name
RELAXNG_ERR_ELEMWRONG
</pre>
<p>Note that this error log is local to the RelaxNG object.  It will only
contain log entries that appeared during the validation.</p>
<p>Similar to XSLT, there's also a less efficient but easier shortcut method to
do one-shot RelaxNG validation:</p>
<pre class="literal-block">
&gt;&gt;&gt; doc.relaxng(relaxng_doc)
True
&gt;&gt;&gt; doc2.relaxng(relaxng_doc)
False
</pre>
<p>libxml2 does not currently support the <a class="reference" href="http://www.thaiopensource.com/relaxng/trang.html">RelaxNG Compact Syntax</a>.
However, the <a class="reference" href="http://www.thaiopensource.com/relaxng/trang.html">trang</a> translator can convert the compact syntax to the
XML syntax, which can then be used with lxml.</p>
</div>
<div class="section">
<h1><a id="xmlschema" name="xmlschema">XMLSchema</a></h1>
<p>lxml.etree also has XML Schema (XSD) support, using the class
lxml.etree.XMLSchema.  The API is very similar to the Relax NG and DTD
classes.  Pass an ElementTree object to construct a XMLSchema validator:</p>
<pre class="literal-block">
&gt;&gt;&gt; f = StringIO('''\
... &lt;xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
... &lt;xsd:element name="a" type="AType"/&gt;
... &lt;xsd:complexType name="AType"&gt;
...   &lt;xsd:sequence&gt;
...     &lt;xsd:element name="b" type="xsd:string" /&gt;
...   &lt;/xsd:sequence&gt;
... &lt;/xsd:complexType&gt;
... &lt;/xsd:schema&gt;
... ''')
&gt;&gt;&gt; xmlschema_doc = etree.parse(f)
&gt;&gt;&gt; xmlschema = etree.XMLSchema(xmlschema_doc)
</pre>
<p>You can then validate some ElementTree document with this.  Like with RelaxNG,
you'll get back true if the document is valid against the XML schema, and
false if not:</p>
<pre class="literal-block">
&gt;&gt;&gt; valid = StringIO('&lt;a&gt;&lt;b&gt;&lt;/b&gt;&lt;/a&gt;')
&gt;&gt;&gt; doc = etree.parse(valid)
&gt;&gt;&gt; xmlschema.validate(doc)
True

&gt;&gt;&gt; invalid = StringIO('&lt;a&gt;&lt;c&gt;&lt;/c&gt;&lt;/a&gt;')
&gt;&gt;&gt; doc2 = etree.parse(invalid)
&gt;&gt;&gt; xmlschema.validate(doc2)
False
</pre>
<p>Calling the schema object has the same effect as calling its validate method.
This is sometimes used in conditional statements:</p>
<pre class="literal-block">
&gt;&gt;&gt; invalid = StringIO('&lt;a&gt;&lt;c&gt;&lt;/c&gt;&lt;/a&gt;')
&gt;&gt;&gt; doc2 = etree.parse(invalid)
&gt;&gt;&gt; if not xmlschema(doc2):
...     print "invalid!"
invalid!
</pre>
<p>If you prefer getting an exception when validating, you can use the
<tt class="docutils literal"><span class="pre">assert_</span></tt> or <tt class="docutils literal"><span class="pre">assertValid</span></tt> methods:</p>
<pre class="literal-block">
&gt;&gt;&gt; xmlschema.assertValid(doc2)
Traceback (most recent call last):
  [...]
DocumentInvalid: Element 'c': This element is not expected. Expected is ( b )., line 1

&gt;&gt;&gt; xmlschema.assert_(doc2)
Traceback (most recent call last):
  [...]
AssertionError: Element 'c': This element is not expected. Expected is ( b )., line 1
</pre>
<p>Error reporting works as for the RelaxNG class:</p>
<pre class="literal-block">
&gt;&gt;&gt; log = xmlschema.error_log
&gt;&gt;&gt; error = log.last_error
&gt;&gt;&gt; print error.domain_name
SCHEMASV
&gt;&gt;&gt; print error.type_name
SCHEMAV_ELEMENT_CONTENT
</pre>
<p>If you were to print this log entry, you would get something like the
following.  Note that the error message depends on the libxml2 version in
use:</p>
<pre class="literal-block">
&lt;string&gt;:1:ERROR::SCHEMAV_ELEMENT_CONTENT: Element 'c': This element is not expected. Expected is ( b ).
</pre>
<p>Similar to XSLT and RelaxNG, there's also a less efficient but easier shortcut
method to do XML Schema validation:</p>
<pre class="literal-block">
&gt;&gt;&gt; doc.xmlschema(xmlschema_doc)
True
&gt;&gt;&gt; doc2.xmlschema(xmlschema_doc)
False
</pre>
</div>
<div class="section">
<h1><a id="id2" name="id2">Schematron</a></h1>
<p>Since version 2.0, lxml.etree features <a class="reference" href="http://www.ascc.net/xml/schematron">Schematron</a> support, using the
class lxml.etree.Schematron.  It requires at least libxml2 2.6.21 to
work.  The API is the same as for the other validators.  Pass an
ElementTree object to construct a Schematron validator:</p>
<pre class="literal-block">
&gt;&gt;&gt; f = StringIO('''\
... &lt;schema xmlns="http://www.ascc.net/xml/schematron" &gt;
...   &lt;pattern name="Sum equals 100%."&gt;
...     &lt;rule context="Total"&gt;
...       &lt;assert test="sum(//Percent)=100"&gt;Sum is not 100%.&lt;/assert&gt;
...     &lt;/rule&gt;
...   &lt;/pattern&gt;
... &lt;/schema&gt;
... ''')

&gt;&gt;&gt; sct_doc = etree.parse(f)
&gt;&gt;&gt; schematron = etree.Schematron(sct_doc)
</pre>
<p>You can then validate some ElementTree document with this.  Like with RelaxNG,
you'll get back true if the document is valid against the schema, and false if
not:</p>
<pre class="literal-block">
&gt;&gt;&gt; valid = StringIO('''\
... &lt;Total&gt;
...   &lt;Percent&gt;20&lt;/Percent&gt;
...   &lt;Percent&gt;30&lt;/Percent&gt;
...   &lt;Percent&gt;50&lt;/Percent&gt;
... &lt;/Total&gt;
... ''')

&gt;&gt;&gt; doc = etree.parse(valid)
&gt;&gt;&gt; schematron.validate(doc)
True

&gt;&gt;&gt; etree.SubElement(doc.getroot(), "Percent").text = "10"

&gt;&gt;&gt; schematron.validate(doc)
False
</pre>
<p>Calling the schema object has the same effect as calling its validate method.
This is sometimes used in conditional statements:</p>
<pre class="literal-block">
&gt;&gt;&gt; is_valid = etree.Schematron(sct_doc)

&gt;&gt;&gt; if not is_valid(doc):
...     print "invalid!"
invalid!
</pre>
<p>Note that libxml2 restricts error reporting to the parsing step (when creating
the Schematron instance).  There is not currently any support for error
reporting during validation.</p>
</div>
</div>
<div class="footer">
<hr class="footer" />
Generated on: 2008-12-12.

</div>
</body>
</html>