David M Smith 的答案是正确的,转换为 CSV 也可以。
经过几次尝试(并编辑了我的答案,因为我在回答之前没有彻底测试),我设法使用一个小的 Python 脚本创建了一个正确的 json 文件,如下所示:
#!python
from __future__ import print_function
import sys
import fileinput
import xml
from xml.dom import minidom
import json
for line in fileinput.input():
try:
xmlDoc = minidom.parseString(line)
print(json.dumps(dict(xmlDoc.childNodes[0].attributes.items())))
except xml.parsers.expat.ExpatError:
print("Unable to process line : ", line, file=sys.stderr)
except KeyboardInterrupt:
sys.exit(0)
然后您可能需要重新启动 shell 来更新路径(或任何其他方法)。
对于最大的文件,我之前需要将它们拆分,因为 BigQuery 接受最大 4GB 的文件。这是完整的流程:
7z x -so ../orig/stackoverflow.com-Posts.7z 2> /dev/null | ./xmltojson.py > PostHistory3.json
split -e -d -C3G --additional-suffix=.json Posts.json Postssplit
ls Postssplit*.json | xargs -ifile gzip file
gsutil cp Postssplit*.json.gz gs://YOURBUCKET
bq --project_id=YOURPROJECT load --source_format=NEWLINE_DELIMITED_JSON YOURDATASET.YOURTABLE gs://YOURBUCKET/Postssplit01.json,gs://YOURBUCKET/Postssplit03.json,gs://YOURBUCKET/Postssplit04.json,#ETCETERA 'Id:INTEGER,PostTypeId:INTEGER,AcceptedAnswerId:INTEGER,ParentId:INTEGER,CreationDate:TIMESTAMP,Score:INTEGER,ViewCount:INTEGER,Body:STRING,OwnerUserId:INTEGER,OwnerDisplayName:STRING,LastEditorUserId:INTEGER,LastEditorDisplayName:STRING,LastEditDate:TIMESTAMP,LastActivityDate:TIMESTAMP,Title:STRING,Tags:STRING,AnswerCount:INTEGER,CommentCount:INTEGER,FavoriteCount:INTEGER,ClosedDate:TIMESTAMP,CommunityOwnedDate:TIMESTAMP'
The gsutil
部分不是强制性的,但我更愿意将文件上传到云存储中,然后导入。这样,如果导入失败我可以重试。
如果 Google 团队的有人正在阅读,那么将其作为公共数据集就太好了:-)
请注意,这不适用于任何 XML,仅适用于格式类似于当前 Stack Exchange 导出格式的 XML。