Reputation: 5132
I want to create a text file from an XML file using XSLT.
Here is my code:
import lxml.etree as ET
dom = ET.parse('a_file.xml')
xslt = ET.parse('a_file.xsl')
transform = ET.XSLT(xslt)
newdom = transform(dom)
print(ET.tostring(newdom, pretty_print=True))
when a_file.xsl
does not contain a root element within the template like this:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<xsl:text>{ this is a test }</xsl:text>
</xsl:template>
</xsl:stylesheet>
the code returns None
, however when I add a root element, then it works ie. <r><xsl:text>{ this is a test }</xsl:text></r>
Upvotes: 0
Views: 198
Reputation: 64969
If you want to create a text file as the result of an XSLT transformation, then there are two changes you need to make to the code in your question.
Firstly, you need to tell the XSLT that it will generate text output. Add the following element to your stylesheet, as a direct child of the <xsl:stylesheet>
element:
<xsl:output method="text" encoding="utf-8" />
Secondly, if you want to convert the result to a string, follow the guidance in the lxml documentation and call str(...)
on it, i.e.
print(str(newdom))
instead of
print(ET.tostring(newdom, pretty_print=True))
Upvotes: 2