Home > Back-end >  lxml.etree.XSLTApplyError: XPath evaluation returned no result
lxml.etree.XSLTApplyError: XPath evaluation returned no result

Time:08-02

I am using lxml (4.9.1) and python (3.8.9) to transform xml with xslt. My code is below:

from lxml import etree
from io import StringIO


def f(context, a):
    return 'Hello '   a


ns = etree.FunctionNamespace('http://www.myns.vn/xslt')
ns.prefix = 'myns'
ns['f'] = f

src = StringIO('<a><b>Text</b><c>See</c></a>')
doc = etree.parse(src)

xslt_root = etree.XML(''' \
    <xsl:stylesheet version="1.0"
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
        <xsl:template match="/">
            <foo><xsl:value-of select="myns:f('Hello')" /></foo>
        </xsl:template>
    </xsl:stylesheet>''')

transform = etree.XSLT(xslt_root)
result_tree = transform(doc)
print(etree.tostring(result_tree, pretty_print=True))

However, it shows below message:

/Users/myuser/PycharmProjects/TestAPI/venv/bin/python /Users/myuser/PycharmProjects/TestAPI/test.py
Traceback (most recent call last):
  File "/Users/myuser/PycharmProjects/TestAPI/test.py", line 25, in <module>
    result_tree = transform(doc)
  File "src/lxml/xslt.pxi", line 602, in lxml.etree.XSLT.__call__
lxml.etree.XSLTApplyError: XPath evaluation returned no result.

Process finished with exit code 1

I did google for several days, but found no glue. Please help!

CodePudding user response:

You need to declare the myns prefix in the stylesheet:

xslt_root = etree.XML(''' \
    <xsl:stylesheet version="1.0"
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        xmlns:myns="http://www.myns.vn/xslt">
        <xsl:template match="/">
            <foo><xsl:value-of select="myns:f('Hello')" /></foo>
        </xsl:template>
    </xsl:stylesheet>''')
  • Related