【发布时间】:2021-03-21 07:37:04
【问题描述】:
我想使用输入 xml 和 xslt 文件生成 xml。我在这里有一个示例输入 xml 和 xslt 文件 https://xsltfiddle.liberty-development.net/aiyned/1>。最后的输出就是我想要的。
基本上input.xml是:
<?xml version="1.0" encoding="utf-8" ?>
<root>
<parent1 value="parent1">
<inserthere value="parent1"/>
</parent1>
<parent2 value="parent2">
<inserthere value="parent2"/>
</parent2>
</root>
input.xslt 是:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output method="xml"/>
<!-- <xsl:variable name="childDoc" select="document('child.xml')"/> -->
<xsl:variable name="childDoc">
<root>
<child1 value="child1"/>
<child2 value="child2"/>
</root>
</xsl:variable>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="inserthere">
<xsl:variable name="currentParent" select="."/>
<xsl:for-each select="$childDoc/root/node()">
<xsl:copy>
<xsl:attribute name="value" select="concat($currentParent/@value,'_',@value)"/>
</xsl:copy>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
输出 xml 是:
<?xml version="1.0" encoding="UTF-8"?><root>
<parent1 value="parent1">
<child1 value="parent1_child1"/>
<child2 value="parent1_child2"/>
</parent1>
<parent2 value="parent2">
<child1 value="parent2_child1"/>
<child2 value="parent2_child2"/>
</parent2>
</root>
问题是该站点使用的是撒克逊引擎,我认为这可能需要许可证。我想使用 lxml 或任何免费的 python 库生成输出 xml。目前当我跑步时
import lxml.etree as ET
dom = ET.parse("input.xml")
xslt = ET.parse("input.xslt")
transform = ET.XSLT(xslt)
newdom = transform(dom)
print(ET.tostring(newdom, pretty_print=True))
我收到以下错误:
newdom = transform(dom)
File "src/lxml/xslt.pxi", line 602, in lxml.etree.XSLT.__call__
lxml.etree.XSLTApplyError: Failed to evaluate the 'select' expression.
我觉得问题是lxml只支持1.0版本?这里有一些 cmets 如何使用 saxon use saxon with python,但我想防止需要 java 或其他外部应用程序。有没有办法只用 python 来完成上述工作?或者有没有办法更新我的 xslt 文件,以便它只使用 lxml 转换函数?
【问题讨论】:
-
childDoc节点实际上在哪里?它们是在单独的 XML 文档中,还是在 XSLT 中列出?它在 XSLT 1.0 中有所作为。 -
目前 childDoc 只是在 xslt 本身中列出
标签: python xml xslt lxml saxon