【发布时间】:2018-04-20 11:23:22
【问题描述】:
我有很大的 XML 文件需要解析、转换成 json 并将其存储在 mongodb 中。
XML 如下所示:
Headers
<response>
<tag1>sssss</tag1>
<tag2>kkkkkk</tag2>
<tag3>aaaaaa</tag3>
</response>
Footers
我只需要两个response 标签之间的文本。当我尝试解析它时会出现问题。代码如下所示:
import pymysql
import re
import json
import xmltodict
from pymongo import MongoClient
# Open Database Connection.
db = pymysql.connect("hjj","fnddd","feoifh","fdfsddfs")
# prepare a cursor object
cursor = db.cursor()
# execute SQL query
cursor.execute("SQL Query")
# Fetch all rows
data = cursor.fetchall()
a = (r'(?=<response>)(.*)(?<=</response>)')
def cleanxml(xml):
file = re.findall(a, xml, re.DOTALL)
return file
data = list(data)
for row in data:
thexml = cleanxml(row[-1])
jsonString = json.dumps(xmltodict.parse(thexml), indent = 4) #error here
上面的代码给了我一个错误:a bytes-like object is required, not 'list'
我尝试将 list(thexml) 转换为 str,如下所示:
thexml = ','.join(str(x) for x in thexml)
在此之后解析也不起作用:
xmltodict.parse(thexml) #no element found: line 1, column 0
我该怎么做?任何帮助表示赞赏。谢谢。
我解决了上述问题只是为了解决另一个问题。解决上述问题的代码:
a = (r'(?=<response>)(.*)(?<=</response>)')
def cleanxml(xml):
if re.findall(a, xml, re.S):
file = re.findall(a, xml, re.S)[0]
else:
file = "<response>NA</response>"
return file
data = list(data)
for row in data:
thexml = cleanxml(row[1])
jsonString = json.dumps(xmltodict.parse(thexml), indent = 4)
d = json.loads(jsonString)
newdict = {"caseid" : row[0]}
newdict.update(d)
jsondata = json.dumps(newdict, indent = 3)
现在,我面临的问题是如何将其插入 mongodb。我尝试使用以下代码,但它不起作用,我不知道如何解决这个问题:
client = MongoClient('localhost', 27017)
db = client.lexnex
collection = db['userdata']
collection.insert(newdict)
我明白了
DeprecationWarning: insert is deprecated. Use insert_one or insert_many instead.
after removing the cwd from sys.path.
当我尝试使用循环插入它时,我仍然收到错误,因为它应该是一个 SON 对象等。有人帮忙吗?确切的错误:document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping
【问题讨论】:
-
该数据不是有效的 XML。 XML 要求在顶层有元素 (
<tag>)(即整个文档包含在<tag>...</tag>中)。 -
以及
cleanxml函数。 -
虽然是个好主意,但“未找到元素”表明您的
cleanxml函数不起作用。如果你打印出它的结果呢?它符合您的期望吗? -
是的,它确实完美。这是其中的一部分:
<response><Header><TransactionId>66215947R1376304</TransactionId> <Status>0</Status> </Header> <RecordCount>1</RecordCount><Records> -
以正确的格式提供 xml 内容
标签: json xml mongodb python-3.x parsing