python 如何把xml文件转化成string

我通过minidom.parseString把一段string转化成xml格式进行解析,现在解析出来进行修改之后,想把xml文件转化成string要怎么做?

你说的不是xml文件吧,是xml对象转化成string吧。

你可以使用toxml()这个方法。

Node.toxml([encoding])
"""
Return the XML that the DOM represents as a string.
With no argument, the XML header does not specify an encoding, and the result is
Unicode string if the default encoding cannot represent all characters in the
document. Encoding this string in an encoding other than UTF-8 is likely
incorrect, since UTF-8 is the default encoding of XML.
With an explicit encoding [1] argument, the result is a byte string in the
specified encoding. It is recommended that this argument is always specified. To
avoid UnicodeError exceptions in case of unrepresentable text data, the
encoding argument should be specified as â€œutf-8”.
Changed in version 2.3: the encoding argument was introduced; see writexml().
"""

如果解决了您的问题请采纳!
如果未解决请继续追问

追问

xml_doc = minidom.parseString(xml_data)
对xml_doc的内容进行修改
print‘xml content’,xml_doc.toxml( encoding='utf-8')
打印xml内容 结果就报错
xml content :error:attributeerror:‘int’ object has no attribute ‘replace’
我哪里弄错了?

温馨提示:内容为网友见解,仅供参考
第1个回答  2015-07-25

你的问题可以直接转化为python如何读取文件,使用这句代码:open('thefile.xml').read( )

下面是例子:

>>> open('D:\\Test.xml',encoding='utf8').read()

不知道为什么,python3.4中读取文件的默认使用GBK,这一点要注意

第2个回答  2015-03-19
可以用toxml()和 toprettyxml()方法啊。
这两个都可以转换成字符串。追问

那如果是elementtree呢?

相似回答