我正在使用lxml python lib。
假设我们有产品xml,例如:
<product id='123' />
并要应用xsl模板:
<xsl:template match="product">
<ssi:include virtual="/ssi/reviews/{@id}"/>
</xsl:template>
ssi:include是一个简单的lxml扩展,可将nginx ssi指令作为注释插入HTML代码中。问题是评估@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'))
最佳答案
尝试使用xsl:attribute
<xsl:template match="product">
<ssi:include>
<xsl:attribute name="virtual">
<xsl:value-of select="concat('/ssi/reviews/',@id)"/>
<xsl:attibute>
</ssi:include>
</xsl:template>