我已经生成了一个带有dom的XML,我想使用lxml来漂亮地打印xml.
I have Generated an XML with dom and i want to use lxml to pretty print the xml.
这是我漂亮地打印xml的代码
this is my code for pretty print the xml
def prettify_xml(xml_str): import lxml.etree as etree root = etree.fromstring(xml_str) xml_str = etree.tostring(root, pretty_print=True) return xml_str我的输出应该是xml格式的字符串.
my output should be an xml formatted string.
我从stactoverflow的某个帖子中获得了此代码.当我编译wit python本身时,这可以完美地工作.但是当我将项目转换为从py2exe创建的二进制文件时(我的二进制文件是带有命名管道的Windows服务).我遇到两个问题:
I got this code from some post in stactoverflow. This works flawlessly when i am compiling wit python itself. But when i convert my project to a binary created from py2exe (my binary is windows service with a namedpipe).I had two problems:
我的服务未启动,我通过在py2exe函数的includes选项中添加lxml.etree解决了此问题.然后我的服务就可以正常启动了.
My service was not starting , i solved this by adding lxml.etree in includes option in py2exe function. then on my service started properly.
在这里调用xml生成时,是我在日志中看到的错误 'module' object has no attribute 'fromstring'
when xml generation in called here, is the error which I am seeing in my log 'module' object has no attribute 'fromstring'
在哪里可以纠正此错误?我的第一个问题的解决方案正确吗?
where do i rectify this error ? And Is my first problem's solution correct ?
我的xml生成代码:
from xml.etree import ElementTree from xml.dom import minidom from xml.etree.ElementTree import Element, SubElement, tostring, XML import lxml.etree def prettify_xml(xml_str): root = lxml.etree.fromstring(xml_str) xml_str = lxml.etree.tostring(root, pretty_print=True) return xml_str def dll_xml(status): try: xml_declaration = '<?xml version="1.0" standalone="no" ?>' rootTagName='response' root = Element(rootTagName) root.set('id' , 'rp001') parent = SubElement(root, 'command', opcode ='-ac') # Create children chdtag1Name = 'mode' chdtag1Value = 'repreport' chdtag2Name='status' chdtag2Value = status fullchildtag1 = ''+chdtag1Name+' value = "'+chdtag1Value+'"' fullchildtag2=''+chdtag2Name+' value="'+chdtag2Value+'"' children = XML('''<root><'''+fullchildtag1+''' /><'''+fullchildtag2+'''/></root> ''') # Add parent parent.extend(children) dll_xml_doc = xml_declaration + tostring(root) dll_xml_doc = prettify_xml(dll_xml_doc) return dll_xml_doc except Exception , error: log.error("xml_generation_failed : %s" % error)推荐答案
尝试使用 PyInstaller 代替py2exe.只需运行python pyinstaller.py YourPath\xml_a.py,我就将程序毫无问题地转换为二进制.exe.
Try to use PyInstaller instead py2exe. I converted your program to binary .exe with no problem just by running python pyinstaller.py YourPath\xml_a.py.
更多推荐
带有py2exe的python lxml
发布评论