使用minidom编写xml文件时,numpy.int64'对象没有属性'replace'

时间:2014-01-09 11:11:08

标签: python xml numpy minidom

我有一个要解析的xml文件。我使用python的minidom解析器做到了这一点。我必须在解析后为特定元素添加属性。现在,我想把文件写回来。我无法做到这一点。

以下是我得到的错误跟踪。 我今天安装了numpy 1.8(win 32 python 2.7)版本。但是,我之前从未尝试过编写xml文件。你能帮忙吗?

以下是代码段:

xmlfile=open(xmlFile,'r')
xmldoc = minidom.parse(xmlFile)
tElements = xmldoc.getElementsByTagName("TEA")
for t in tElements:
    if(t.childNodes):
        print t.nodeType
        dataList = t.childNodes[0].data
        for data, csvData in product(dataList, clusterDataList):
            if(data == csvData[1]):
              t.setAttribute("cluster",csvData[0])
xmlfile.close()
fileWriter=open("sujatha_new.xml",'w')

xmldoc.writexml(fileWriter)
fileWriter.close()

以下是例外:

Traceback (most recent call last):
  File "C:\Users\w44ylqrl\workspace\Python\Test\T\XMLConverter.py", line 215, in <module>
    addClusterInfo('..\\T\\preprocessed_For_Clustering\\outputs\\sujatha-new.csv', '..\\T\\xml\\sujatha.xml')
  File "C:\Users\w44ylqrl\workspace\Python\Test\T\XMLConverter.py", line 48, in addClusterInfo
    xmldoc.writexml(fileWriter)
  File "C:\Python27\Lib\xml\dom\minidom.py", line 1752, in writexml
    node.writexml(writer, indent, addindent, newl)
  File "C:\Python27\Lib\xml\dom\minidom.py", line 817, in writexml
    node.writexml(writer, indent+addindent, addindent, newl)
  File "C:\Python27\Lib\xml\dom\minidom.py", line 817, in writexml
    node.writexml(writer, indent+addindent, addindent, newl)
  File "C:\Python27\Lib\xml\dom\minidom.py", line 817, in writexml
    node.writexml(writer, indent+addindent, addindent, newl)
  File "C:\Python27\Lib\xml\dom\minidom.py", line 817, in writexml
    node.writexml(writer, indent+addindent, addindent, newl)
  File "C:\Python27\Lib\xml\dom\minidom.py", line 817, in writexml
    node.writexml(writer, indent+addindent, addindent, newl)
  File "C:\Python27\Lib\xml\dom\minidom.py", line 807, in writexml
    _write_data(writer, attrs[a_name].value)
  File "C:\Python27\Lib\xml\dom\minidom.py", line 296, in _write_data
    data = data.replace("&", "&amp;").replace("<", "&lt;"). \
AttributeError: 'numpy.int64' object has no attribute 'replace'

1 个答案:

答案 0 :(得分:0)

所有python XML实现都不允许您序列化非字符串表示,但如果您想将etree等滥用为树状数据结构,则其中一些将允许您分配它们。有些(如lxml)甚至不允许你分配它们。只需将其设为字符串:

t.setAttribute("cluster",str(csvData[0]))

它会起作用。如果你也反序列化这些,你需要在加载后将值转换回int。