私はlxml python libを使用しています。
次のような製品 xml があるとします。
<product id='123' />
そして、xsl テンプレートを適用したい:
<xsl:template match="product">
<ssi:include virtual="/ssi/reviews/{@id}"/>
</xsl:template>
ssi:include は、nginx ssi 命令をコメントとして HTML コードに挿入する単純な lxml 拡張機能です。問題は、@id を評価し、属性を virtual="/ssi/include/123" として渡すことです。方法はありますか?私は解決策を見つけて、今ではそれを使用しています:
import lxml.etree
import re
from copy import deepcopy
ns = '{ssi}'
# ssi extensions
class SsiExtElement(lxml.etree.XSLTExtension):
def execute(self, context, self_node, input_node, output_parent):
_, tag = self_node.tag.split('}')
tmp = lxml.etree.Element('tmp')
for k, v in self_node.attrib.items():
if re.search('\{(.*)\}', v): #here we search {xpath} values to evaluate
elem = deepcopy(input_node)
matches = re.findall('\{(.*)\}', v)
for match in matches:
v = v.replace('{%s}' % match, elem.xpath(match)[0])
tmp.set(k, v)
self.process_children(context, output_parent=tmp)
attrs = ' '.join(u'%s="%s"' % (k, v) for k, v in tmp.attrib.items())
ssi = lxml.etree.Comment(u'#%s %s' % (tag, attrs))
output_parent.append(ssi)
for node in tmp:
output_parent.append(node)
if (self_node.tag.replace(ns,'') in ('if', 'else', 'elif')
and self_node.getnext().tag.replace(ns, '') not in ('else', 'elif')):
output_parent.append(lxml.etree.Comment(u'#endif'))