美好的一天!需要在Python中使用xslt转换xml。我在php中有一个示例代码。
如何在Python中实现它或在哪里找到类似的东西?谢谢!
$xmlFileName = dirname(__FILE__)."example.fb2";
$xml = new DOMDocument();
$xml->load($xmlFileName);
$xslFileName = dirname(__FILE__)."example.xsl";
$xsl = new DOMDocument;
$xsl->load($xslFileName);
// Configure the transformer
$proc = new XSLTProcessor();
$proc->importStyleSheet($xsl); // attach the xsl rules
echo $proc->transformToXML($xml);
答案 0 :(得分:89)
使用lxml,
import lxml.etree as ET
dom = ET.parse(xml_filename)
xslt = ET.parse(xsl_filename)
transform = ET.XSLT(xslt)
newdom = transform(dom)
print(ET.tostring(newdom, pretty_print=True))
答案 1 :(得分:5)
LXML是一个广泛使用的高性能库,用于基于libxml2和libxslt的python中的XML处理 - 它包含XSLT as well的工具。
答案 2 :(得分:1)
最好的方法是使用lxml,但它只支持XSLT 1
import os
import lxml.etree as ET
inputpath = "D:\\temp\\"
xsltfile = "D:\\temp\\test.xsl"
outpath = "D:\\output"
for dirpath, dirnames, filenames in os.walk(inputpath):
for filename in filenames:
if filename.endswith(('.xml', '.txt')):
dom = ET.parse(inputpath + filename)
xslt = ET.parse(xsltfile)
transform = ET.XSLT(xslt)
newdom = transform(dom)
infile = unicode((ET.tostring(newdom, pretty_print=True)))
outfile = open(outpath + "\\" + filename, 'a')
outfile.write(infile)
要使用XSLT 2,您可以检查Use saxon with python
中的选项