LXML和XSL document()函数

时间:2012-01-12 08:23:10

标签: python xslt lxml

您好我有以下文件:

merge.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))

merge.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

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

2 个答案:

答案 0 :(得分:8)

您需要注册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))

答案 1 :(得分:6)

为什么不简单地这样做?

from lxml import etree

xml_input = etree.parse("a.xml")
xslt_root = etree.parse("merge.xsl")
transform = etree.XSLT(xslt_root)
print str(transform(xml_input))

更直接,不需要解析器。