且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将XML转换为文本

更新时间:2023-02-06 16:13:30

由于OP包含其Python代码,因此已更新.

updated now that OP's included his Python code.

您的问题是lxml.etree.tostring.write方法仅在XML上有意义,而在output method="text"的XSLT结果中却没有意义,而output method="text"可能没有像XML那样的单个根元素.由于某些令人困惑的原因,函数 do 具有一个method=关键字参数,但是它没有任何用处.

Your problem is that lxml.etree.tostring and also the .write method are only meaningful on XML, not on an XSLT result with output method="text" which might not have a single root element like XML does. For some confusing reason, the functions do have a method= keyword argument but it does not do anything useful.

这是您应该做的:

import lxml.etree as etree
data = etree.parse('data.xml')
transform = etree.XSLT(etree.parse('txt.xslt'))
res = transform(data)
bytes(res)

b'\nCEO and 1Director of Operations and 2Human Resources Manager and 3\n'

如果您对真实示例感兴趣,请我最近做了补丁.

If you're interested in a real world example, I recently made a patch.