相关疑难解决方法(0)

在Python中打印XML

在Python中打印xml的最佳方法(甚至是各种方法)是什么?

python xml pretty-print

401
推荐指数
14
解决办法
33万
查看次数

什么是从python字符串中删除空行的快速单行程序?

我在python字符串中有一些包含无关空行的代码.我想从字符串中删除所有空行.什么是最pythonic的方式来做到这一点?

注意:我不是在寻找一般的代码重新格式化程序,只需要快速的一个或两个内容.

谢谢!

python string line-endings

57
推荐指数
5
解决办法
5万
查看次数

如何让Python的ElementTree打印到XML文件?

背景

我正在使用SQLite访问数据库并检索所需的信息.我在Python 2.6版中使用ElementTree来创建包含该信息的XML文件.

import sqlite3
import xml.etree.ElementTree as ET

# NOTE: Omitted code where I acccess the database,
# pull data, and add elements to the tree

tree = ET.ElementTree(root)

# Pretty printing to Python shell for testing purposes
from xml.dom import minidom
print minidom.parseString(ET.tostring(root)).toprettyxml(indent = "   ")

#######  Here lies my problem  #######
tree.write("New_Database.xml")
Run Code Online (Sandbox Code Playgroud)

尝试

我已经尝试使用tree.write("New_Database.xml", "utf-8")上面代码的最后一行,但它根本没有编辑XML的布局 - 它仍然是混乱的混乱.

我还决定摆弄并尝试做:而不是将其打印到Python shell,这给出了错误AttributeError:'unicode'对象没有属性'write'.
tree = minidom.parseString(ET.tostring(root)).toprettyxml(indent = " ")

问题

当我将我的树写到最后一行的XML文件时,是否有一种方法可以像在Python shell中那样打印到XML文件?

我可以toprettyxml()在这里使用,还是有不同的方法来做到这一点?

python xml pretty-print elementtree python-2.6

30
推荐指数
6
解决办法
5万
查看次数

使用minidom.toprettyxml时空行

我一直在使用minidom.toprettyxml来美化我的xml文件.当我创建XML文件并使用这个方法时,所有工作都很好,但是如果我在修改了xml文件之后使用它(例如我添加了一个额外的节点)然后我将它写回XML ,我得到空行,每次我更新它,我越来越空行......

我的代码:

file.write(prettify(xmlRoot))


def prettify(elem):
    rough_string = xml.tostring(elem, 'utf-8') //xml as ElementTree
    reparsed = mini.parseString(rough_string) //mini as minidom
    return reparsed.toprettyxml(indent=" ")
Run Code Online (Sandbox Code Playgroud)

结果:

<?xml version="1.0" ?>
<testsuite errors="0" failures="3" name="TestSet_2013-01-23 14_28_00.510935" skip="0"     tests="3" time="142.695" timestamp="2013-01-23 14:28:00.515460">




    <testcase classname="TC test" name="t1" status="Failed" time="27.013"/>




    <testcase classname="TC test" name="t2" status="Failed" time="78.325"/>


    <testcase classname="TC test" name="t3" status="Failed" time="37.357"/>
</testsuite>
Run Code Online (Sandbox Code Playgroud)

有什么建议 ?

谢谢.

python xml pretty-print minidom

16
推荐指数
2
解决办法
1万
查看次数

从命令行合并多个XML文件

我有几个xml文件.它们都具有相同的结构,但由于文件大小而被拆分.所以,让我们说我有A.xml,B.xml,C.xmlD.xml和要合并/它们合并到combined.xml,使用命令行工具.

A.XML

<products>
    <product id="1234"></product>
    ...
</products>
Run Code Online (Sandbox Code Playgroud)

B.XML

<products>
  <product id="5678"></product>
  ...
</products>
Run Code Online (Sandbox Code Playgroud)

等等

xml merge command-line

14
推荐指数
2
解决办法
2万
查看次数

用于XML字符串的Python pretty XML打印机

我使用python生成一个冗长而丑陋的XML字符串,我需要通过漂亮的打印机对其进行过滤以使其看起来更好.

我发现这篇文章适用于python漂亮的打印机,但是我必须将XML字符串写入要回读的文件以使用这些工具,如果可能的话我想避免使用这些工具.

什么python漂亮的工具可以在字符串上工作?

python xml pretty-print

7
推荐指数
2
解决办法
2万
查看次数