Skip to content

Instantly share code, notes, and snippets.

@martin-honnen
Created May 23, 2024 15:23
Show Gist options
  • Select an option

  • Save martin-honnen/baa79449b27317d33e697a15ee2d67f9 to your computer and use it in GitHub Desktop.

Select an option

Save martin-honnen/baa79449b27317d33e697a15ee2d67f9 to your computer and use it in GitHub Desktop.
XSLT1PythonExample1OutputMethodText
from lxml import etree as ET
xml = ET.XML('''<order id="1021">
<items>
<item code="11">
<quantity>2</quantity>
<price>50</price>
</item>
<item code="21">
<quantity>1</quantity>
<price>250</price>
</item>
<item code="13">
<quantity>4</quantity>
<price>100</price>
</item>
</items>
<status>3</status>
</order>''')
xslt = ET.XML('''<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<!-- Template to match the root 'order' element -->
<xsl:template match="/order">
<!-- Start bracket for the array -->
<xsl:text>[</xsl:text>
<!-- Iterate over each item -->
<xsl:for-each select="items/item">
<!-- Output the code attribute -->
<xsl:value-of select="@code"/>
<!-- If not the last item, add a comma and space -->
<xsl:if test="position() != last()">
<xsl:text>, </xsl:text>
</xsl:if>
</xsl:for-each>
<!-- End bracket for the array -->
<xsl:text>]</xsl:text>
</xsl:template>
</xsl:stylesheet>''')
transformer = ET.XSLT(xslt)
result = transformer(xml)
print(str(result))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment