Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 and xml/xslt libraries

In python 2.6 I did this to achieve an xsl tranform

    import libxml2
    import libxslt
    ...
    styledoc = libxml2.parseFile(my_xslt_file)
    style = libxslt.parseStylesheetDoc(styledoc)
    doc = libxml2.parseDoc(siri_response_data)
    result = style.applyStylesheet(doc, None)
    ...

What would be the equivalent in Python 3.2?

I ask because it seems that lnxml and libxslt are not available in python3.2. I have heard of lxml - is this a direct equivalent of libxml2 + libxslt or does it have different calling patterns (needing rewriting of the code)?

like image 824
barking.pete Avatar asked Jan 23 '12 11:01

barking.pete


People also ask

What are XML libraries for Python?

XML, or Extensible Mark-up Language, is a set of rules for encoding data and documents in a way that is both human and machine readable. XML excels where you need to transfer data between different systems, as there is almost always going to be an XML parser available.

What is the name of Python built in module for XML processing?

The xml.etree.ElementTree module implements a simple and efficient API for parsing and creating XML data. Changed in version 3.3: This module will use a fast implementation whenever available.

Is XSLT obsolete?

The XslTransform class is obsolete in . NET Framework version 2.0. The XslCompiledTransform class is a new implementation of the XSLT engine.

What is LXML library?

lxml is a Python library which allows for easy handling of XML and HTML files, and can also be used for web scraping. There are a lot of off-the-shelf XML parsers out there, but for better results, developers sometimes prefer to write their own XML and HTML parsers.


1 Answers

The analog of your code using lxml:

from lxml import etree

# ...    
styledoc = etree.parse(my_xslt_file)
transform = etree.XSLT(styledoc)
doc = etree.fromstring(siri_response_data)
result = transform(doc)
# ...

lxml lists support for Python 3.2

lxml uses libxml2/libxslt under the hood so results should be the same. It uses Cython to generate C extensions that work both on Python 2.x and 3.x from the same source, example.

like image 199
jfs Avatar answered Dec 02 '22 02:12

jfs