gpt4 book ai didi

python - LXML 和 XSL document() 函数

转载 作者:太空狗 更新时间:2023-10-29 22:09:55 24 4
gpt4 key购买 nike

您好,我有以下文件:

合并.py:

from lxml import etree

xml_input = etree.XML(open('a.xml', 'r').read())
xslt_root = etree.XML(open('merge.xsl', 'r').read())
transform = etree.XSLT(xslt_root)
print str(transform(xml_input))

合并.xsl:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<merge>
<xsl:copy-of select="."/>
<xsl:copy-of select="document('b.xml')"/>
</merge>
</xsl:template>

a.xml:

<?xml version="1.0" encoding="ISO-8859-1"?>
<a>
<test id="1"/>
</a>

b.xml:

<?xml version="1.0" encoding="ISO-8859-1"?>
<b>
<test id="2"/>
</b>

这 4 个文件在同一目录中,当我调用 merge.py 时出现错误:

lxml.etree.XSLTApplyError: Cannot resolve URI string://__STRING__XSLT__/b.xml

有什么想法吗?我做错了什么?

最佳答案

您需要注册一个 URI 解析器。参见 the documentation .

可能是这样的(未经测试):

class FileResolver(etree.Resolver):
def resolve(self, url, pubid, context):
return self.resolve_filename(url, context)

parser = etree.XMLParser()
parser.resolvers.add(FileResolver())
xml_input = etree.parse(open('a.xml','r'), parser)
xslt_root = etree.parse(open('merge.xsl','r'), parser)
transform = etree.XSLT(xslt_root)
print str(transform(xml_input))

关于python - LXML 和 XSL document() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8831941/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com