不包含根元素容器时 XSLT 不工作

XSLT not working when no root element container is included

我想使用 XSLT 从 XML 文件创建一个文本文件。

这是我的代码:

import lxml.etree as ET

dom = ET.parse('a_file.xml')
xslt = ET.parse('a_file.xsl')
transform = ET.XSLT(xslt)
newdom = transform(dom)
print(ET.tostring(newdom, pretty_print=True))

a_file.xsl 不包含像这样的模板中的根元素时:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">

    <xsl:text>{ this is a test }</xsl:text>
    
    </xsl:template>
</xsl:stylesheet>

代码 returns None,但是当我添加一个根元素时,它就起作用了,即。 <r><xsl:text>{ this is a test }</xsl:text></r>

如果您想创建一个文本文件作为 XSLT 转换的结果,那么您需要对问题中的代码进行两处更改。

首先,您需要告诉XSLT 它将生成文本输出。将以下元素添加到您的样式表中,作为 <xsl:stylesheet> 元素的直接子元素:

    <xsl:output method="text" encoding="utf-8" />

其次,如果要将结果转换为字符串,请按照lxml documentation中的指导并对其调用str(...),即

print(str(newdom))

而不是

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