python 如何把xml文件转化成string

发布网友

我来回答

3个回答

热心网友

你说的不是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 introced; 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’
我哪里弄错了?

热心网友

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

下面是例子:

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

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

热心网友

可以用toxml()和 toprettyxml()方法啊。
这两个都可以转换成字符串。追问那如果是elementtree呢?

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com