3

I have data that comes as an XML file. I have also been provided an XSLT to transform the XML to HTML. I can use lxml to perform the conversion, however, I want to alter some of the HTML tags after the transformation. How do I convert this new etree into HtmlElements so that I can specifically use certain methods like .cssselect() and so on.

6
  • 2
    is not it easier to change xslt code? Commented Jun 21, 2013 at 16:04
  • No. I want to get the filenames from the newly created <img> tags so that I can Base64encode them into the new html file. Stuff like that. Commented Jun 21, 2013 at 16:14
  • Hi, could you perhaps send me the code you use to transform the xml and xslt to html? I cant find anything on the net. Commented Oct 10, 2013 at 6:23
  • lxml.de/xpathxslt.html#xslt Commented Oct 10, 2013 at 19:21
  • @OozeMeister : I have also been provided an XSLT to transform the XML to HTML. Can you please share the python code you used for this. Commented Jun 5, 2015 at 11:43

1 Answer 1

2
>>> import lxml.etree
>>> import lxml.html
>>>
>>> xmlstring = '''\
... <?xml version='1.0' encoding='ASCII'?>
... <root><a class="here">link1</a><a class="there">link2</a></root>
... '''
>>> root = lxml.etree.fromstring(xmlstring)
>>> root.cssselect('a.here')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'lxml.etree._Element' object has no attribute 'cssselect'

lxml.etree.tostring(root) -> lxml.html.fromstring(..)

>>> root = lxml.html.fromstring(lxml.etree.tostring(root))
>>> root.cssselect('a.here')
[<Element a at 0x2989308>]

Get XML output:

>>> print lxml.etree.tostring(root, xml_declaration=True)
<?xml version='1.0' encoding='ASCII'?>
<root><a class="here">link1</a><a class="there">link2</a></root>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.