使用此代码:
from lxml import etree
with open( 'C:\\Python33\\projects\\xslt', 'r' ) as xslt, open( 'C:\\Python33\\projects\\result', 'a+' ) as result, open( 'C:\\Python33\\projects\\xml', 'r' ) as xml:
s_xml = xml.read()
s_xslt = xslt.read()
transform = etree.XSLT(etree.XML(s_xslt))
out = transform(etree.XML(s_xml))
result.write(out)
我收到此错误:
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
from projects.xslt_transform import trans
File ".\projects\xslt_transform.py", line 17, in <module>
transform = etree.XSLT(etree.XML(s_xslt))
File "xslt.pxi", line 409, in lxml.etree.XSLT.__init__ (src\lxml\lxml.etree.c:150256)
lxml.etree.XSLTParseError: Invalid expression
这对xml / xslt文件可以与其他工具一起使用。
此外,我必须删除两个文件的顶部声明中的encoding属性,以便不得:
ValueError: Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration.
可以相关吗?
修改:
这也不起作用(我得到同样的错误):
with open( 'C:\\Python33\\projects\\xslt', 'r',encoding="utf-8" ) as xslt, open( 'C:\\Python33\\projects\\result', 'a+',encoding="utf-8" ) as result, open( 'C:\\Python33\\projects\\xml', 'r',encoding="utf-8" ) as xml:
s_xml = etree.parse(BytesIO(bytes(xml.read(),'UTF-8')))
s_xslt = etree.parse(BytesIO(bytes(xslt.read(),'UTF-8')))
transform = etree.XSLT(s_xslt)
out = transform(s_xml)
print(out.tostring())
阅读lxml源代码:这会返回一个异常:
xslt.xsltParseStylesheetDoc(c_doc)
所以它似乎是一个实际的解析错误。它可以与名称空间相关吗?
编辑已解决:
s_xml = etree.parse(xml.read())
s_xslt = etree.parse(xslt.read())
感谢马拉克
答案 0 :(得分:7)
解析XML比“打开文本文件,将生成的字符串填充到etree”更复杂。
XML文件是DOM树的序列化表示。它们不能作为文本处理,即使它们是文本文件的形状。它们采用多字节编码,并找出某个文件使用的编码是微不足道的。
XML解析器内置了适当的检测机制,因此它们应该用于打开XML文件。基本的open()
+ read()
调用不足以正确处理文件内容。
lxml.etree
提供the parse()
function,可以接受多种参数类型:
- 打开文件对象(确保以二进制模式打开)
- 一个类文件对象,其中.read(byte_count)方法在每次调用时返回一个字节字符串
- 文件名字符串
- HTTP或FTP URL字符串
然后将正确地将关联的文档解析回DOM树。
您的代码应该更像这样:
from lxml import etree
f_xsl = 'C:\\Python33\\projects\\xslt'
f_xml = 'C:\\Python33\\projects\\xml'
f_out = 'C:\\Python33\\projects\\result'
transform = etree.XSLT(etree.parse(f_xsl))
result = transform(etree.parse(f_xml))
result.write(f_out)