如何在Python中使用XSLT转换XML文件? [英] How to transform an XML file using XSLT in Python?

查看:308
本文介绍了如何在Python中使用XSLT转换XML文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天!需要在Python中使用xslt转换xml。我在php中有一个示例代码。

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

如何在Python中实现此功能或在何处找到类似内容?谢谢!

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

$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);


推荐答案

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

这篇关于如何在Python中使用XSLT转换XML文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆