Home > Back-end >  Transform xml using xslt in python
Transform xml using xslt in python

Time:10-14

I have seen the example and solution in the website but my coding still have some problem. I dont know how to change it. This is my xml coding which save as testing.xml

<?xml version="1.0"?>
<Menu>
 <Title>Snacks</Title>
 <Icecreams>
 <Icecream>Nutella brownie</Icecream>
 <Icecream>Blackcurrent</Icecream>
 </Icecreams>
 <Beverages>
 <Beverage>Fresh Mango Shake</Beverage>
 <Beverage>Cold coffee</Beverage>
 </Beverages>
<Title>Starters</Title>
 <NonvegStarter>
 <Nonveg>Chilly chicken</Nonveg>
 <Nonveg>Chicken Urwal</Nonveg>
 </NonvegStarter>
 <vegStarter>
 <veg>Veg Manchurian</veg>
 <veg>Spring roll</veg>
 </vegStarter>
</Menu>

And this is my xsl coding save as testing.xsl

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:strip-space elements="*" />
 <xsl:output method="text" indent="no" />
<xsl:template match="/">
 Menu:<xsl:value-of select="/Menu/Title"/>
 Icecreams: <xsl:apply-templates select="/Menu/Icecreams/Icecream"/>
 </xsl:template>
<xsl:template match="Icecream"><xsl:value-of select="." />
 </xsl:template>
</xsl:stylesheet>

I use the recommend coding which is

import lxml.etree as ET

dom = ET.parse(testing.xml)
xslt = ET.parse(testing.xsl)
transform = ET.XSLT(xslt)
newdom = transform(dom)
print(ET.tostring(newdom, pretty_print=True))

And it will output the error with "name "testing" is not defined"

CodePudding user response:

ET.parse(testing.xml) should be ET.parse('testing.xml'). The same change needs to be done for the second line.

I don't understand what you want to achieve with print(ET.tostring(newdom, pretty_print=True)) with output method text in the XSLT.

Anyway, the lxml documentation suggestes using newdom.write_output e.g. newdom.write_output('result.txt') is a better way to deal with outputting XSLT transformation results.

  • Related