我正在使用 lxml python lib。
假设我们有产品 xml,例如:
<product id='123' />
并想应用 xsl 模板:
<xsl:template match="product">
<ssi:include virtual="/ssi/reviews/{@id}"/>
</xsl:template>
ssi:include 是一个简单的 lxml 扩展,它在 HTML 代码中插入 nginx ssi 指令作为注释。问题是评估@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'))