如何在 Python 中使用 XSLT 转换 XML 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16698935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:23:51  来源:igfitidea点击:

How to transform an XML file using XSLT in Python?

pythonxmlxsltconverter

提问by aphex

Good day! Need to convert xml using xslt in Python. I have a sample code in php.

再会!需要在 Python 中使用 xslt 转换 xml。我在 php 中有一个示例代码。

How to implement this in Python or where to find something similar? Thank you!

如何在 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);

采纳答案by unutbu

Using lxml,

使用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))

回答by miku

LXMLis a widely used high performance library for XML processing in python based on libxml2 and libxslt - it includes facilities for XSLT as well.

LXML是一个广泛使用的高性能库,用于在基于 libxml2 和 libxslt 的 Python 中进行 XML 处理 - 它也包括用于XSLT 的工具

回答by Maliqf

The best way is to do it using lxml, but it only support XSLT 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)

to use XSLT 2 you can check options from Use saxon with python

要使用 XSLT 2,您可以检查Use saxon with python 中的选项