Рассмотрим параметризованное решение XSLT с использованием стороннего модуля Python, lxml
, где вы передаете новые значения ширины и высоты из Python для динамического применения формулы до XML атрибутов.
XSLT (сохранить как файл .xsl)
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" encoding="utf-8"/>
<xsl:strip-space elements="*"/>
<!-- PARAMS WITH DEFAULTS -->
<xsl:param name="new_width" select="1080"/>
<xsl:param name="new_height" select="720"/>
<!-- IDENTITY TRANSFORM -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!-- WIDTH AND HEIGHT ATTRS CHANGE -->
<xsl:template match="image">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:attribute name="width"><xsl:value-of select="$new_width"/></xsl:attribute>
<xsl:attribute name="height"><xsl:value-of select="$new_height"/></xsl:attribute>
<xsl:apply-templates select="node()"/>
</xsl:copy>
</xsl:template>
<!-- X ATTRS CHANGE -->
<xsl:template match="box/@xbr|box/@xtl">
<xsl:variable select="ancestor::image/@width" name="curr_width"/>
<xsl:attribute name="{name(.)}">
<xsl:value-of select="format-number(. div ($curr_width div $new_width) , '#.00000')"/>
</xsl:attribute>
</xsl:template>
<!-- Y ATTRS CHANGE -->
<xsl:template match="box/@ybr|box/@ytl">
<xsl:variable select="ancestor::image/@height" name="curr_height"/>
<xsl:attribute name="{name(.)}">
<xsl:value-of select="format-number(. div ($curr_height div $new_height), '#.00000')"/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
Python (нет for
l oop или if
logi c)
import lxml.etree as et
# LOAD XML AND XSL SCRIPT
xml = et.parse('Input.xml')
xsl = et.parse('Script.xsl')
# PASS PARAMETERS TO XSLT
transform = et.XSLT(xsl)
result = transform(xml, new_width = et.XSLT.strparam(str(1080)),
new_height = et.XSLT.strparam(str(720)))
# SAVE RESULT TO FILE
with open("Output.xml", 'wb') as f:
f.write(result)
Выход
<?xml version="1.0" encoding="utf-8"?>
<annotations>
<image height="720" id="3" name="C_00080.jpg" width="1080">
<box label="Objects" occluded="0" xbr="475.90767" xtl="461.54367" ybr="388.33698" ytl="369.05463">
<attribute name="Class">B</attribute>
</box>
<box label="Objects" occluded="0" xbr="593.00248" xtl="571.67992" ybr="397.74140" ytl="372.78098">
<attribute name="Class">A</attribute>
</box>
</image>
</annotations>