XPath collection()函数是否与lxml和XSLT一起工作?

2024-04-28 22:46:44 发布

您现在位置:Python中文网/ 问答频道 /正文

最近,我尝试使用lxml包和包含XPath collection()函数变量的XSL样式表转换XML文件,但在运行代码时出现以下错误:

lxml.etree.XSLTApplyError: Failed to evaluate the expression of variable 'name'.

以下是我的文件的详细信息:

  • XML源:catalog.XML
    <?xml version="1.0" encoding="UTF-8"?>
    <collection>
         <doc href="./IR_041698.xml"/>
         <doc href="./IR_051379.xml"/>
     </collection>
  • XSL文件:test.XSL
    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
    xmlns:tei="http://www.tei-c.org/ns/1.0"
    exclude-result-prefixes="tei">

    <xsl:strip-space elements="*"/>
    <xsl:output indent="yes" method="xml"/>

    <xsl:template match="/">

     <xsl:variable name="name" select="collection('catalog.xml')/descendant::archdesc/did/origination/persname/text()"/>

     <teiHeader xmlns="http://www.tei-c.org/ns/1.0">
                    <fileDesc>
                        <titleStmt>
                            <title>
                                <xsl:value-of select="$name"/>
                            </title>
                       </titleStmt>
                   </fileDesc>
      </teiHeader>
   </xsl:template>

</xsl:stylesheet>

  • Python代码:
from lxml import etree as ET

source = ET.parse("catalog.xml")
xslt = ET.parse("test.xsl")

transform = ET.XSLT(xslt)
newdom = transform(source)

print(ET.tostring(newdom, pretty_print=True))

我有点惊讶,因为当我在oxygenxml编辑器下启动转换时,它可以工作,但在Python中不能

你有什么建议吗?XPath collection()函数在lxml中有问题吗

先谢谢你


Tags: 文件namehttpversionwwwxmlteilxml
1条回答
网友
1楼 · 发布于 2024-04-28 22:46:44

collection函数是XPath和XSLT2及更高版本的一部分,因此lxml不支持它。但是,在XSLT中,可以使用document函数作为document(document('catalog.xml')/*/doc/@href))来选择由catalog.xml文档中doc元素节点的href属性选择的文档的“集合”

SAXON 9.9也可以作为Python模块https://www.saxonica.com/saxon-c/doc/html/saxonc.html作为SAXON C1.2.1的一部分(下载http://saxonica.com/download/c.xml,文档:http://www.saxonica.com/saxon-c/documentation/index.html),因此如果您想在Python中使用XSLT 3,可以考虑从LXML切换到Sxxon C。p>

相关问题 更多 >