Python中文
首页
教程
问答
标签
搜索
登录
注册
python xml pretty print不工作
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>我通过从列表中添加一些节点和值来更改一些xml。我可以成功地创建所有新的标记和值,我在贡献者标记之间创建它们,但是当我将xml保存到一个新文件中时,我创建的标记都在一行上。下面是我的代码示例:</p> <pre><code>templateXml = """<?xml version="1.0" encoding="utf-8" standalone="yes"?> <package> <delivery_type>new</delivery_type> <feature> <feature_type>Movie</feature_type> <contributors> </contributors> </package>""" from lxml import etree tree = etree.fromstring(templateXml) node_video = tree.xpath('//feature/contributors')[0] for cast in castList: pageElement = etree.SubElement(node_video, 'contributor') node_video1 = tree.xpath('//feature/contributors/contributor')[0] pageElement.attrib['type'] = 'cast' pageElement1 = etree.SubElement(pageElement, 'name') pageElement1.text = cast.text pageElement2 = etree.SubElement(pageElement, 'role') pageElement2.text = "actor" xmlFileOut = '/Users/User1/Desktop/Python/Done.xml' with open(xmlFileOut, "w") as f: f.write(etree.tostring(tree, pretty_print = True, xml_declaration = True, encoding='UTF-8', standalone="yes")) </code></pre> <p>以下是保存的xml文件:</p> ^{pr2}$ <p>我在打开xml文件以使用以下代码工作时解决了此问题:</p> <pre><code>from lxml import etree parser = etree.XMLParser(remove_blank_text=True) # makes pretty print work path3 = 'path_to_xml_file' open(path3) tree = etree.parse(path3, parser) root = tree.getroot() tree.write(xmlFileOut, pretty_print = True, xml_declaration = True, encoding = 'UTF-8') </code></pre> <p>这是可行的,但是如何让它与字符串xml一起工作呢?在</p>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>一个简单的解决方案可能是使用StringIO:</p> <pre><code>from StringIO import StringIO from lxml import etree parser = etree.XMLParser(remove_blank_text=True) tree = etree.parse(StringIO(templateXml), parser) </code></pre>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
无法使用Django/mongoengine连接到MongoDB(身份验证失败)
9 回答
无法使用Django\u mssql\u后端迁移到外部hos
7 回答
无法使用Django&Python3.4连接到MySql
9 回答
无法使用Django+nginx上载媒体文件
10 回答
无法使用Django1.6导入名称模式
6 回答
无法使用Django1.7和mongodb登录管理站点
2 回答
无法使用Djangoadmin创建项目,进程使用了错误的路径,因为我事先安装了错误的Python
7 回答
无法使用Djangockedi验证CBV中的字段
6 回答
无法使用Djangocketditor上载图像(错误400)
10 回答
无法使用Djangocron进行函数调用
8 回答
无法使用Djangofiler djang上载文件
4 回答
无法使用Djangokronos
7 回答
无法使用Djangomssql provid
1 回答
无法使用Djangomssql连接到带有Django 1.11的MS SQL Server 2016
10 回答
无法使用Djangomssq迁移Django数据库
10 回答
无法使用Djangonox创建用户
9 回答
无法使用Djangopyodb从Django查询SQL Server
2 回答
无法使用Djangopython3ldap连接到ldap
3 回答
无法使用Djangoredis连接到redis
5 回答
无法使用Django中的FK创建新表
7 回答