我是一个总菜鸟,没有其他办法解决这个问题所以我需要用Python来做。我需要解析一个xml文件。当文件存储在本地时,这可以正常工作。但是,我需要能够在Google云端存储中打开该文件。
请看我的代码。我不知道如何将blob作为文件名传递给ElementTree。如果我使用blob.download_as_string(),我将获取xml文件的内容作为名称。哪个是文件太长和错误的路径。
import xml.etree.ElementTree as ET
from google.cloud import storage
client = storage.Client()
#My bucket
bucket = client.get_bucket('import')
# This is my file
blob = bucket.get_blob('/xml/Profit.xml')
xml_file = blob.download_as_string()
#xml_file is now looooong string and not what I want
root = ET.parse(xml_file)
#This doesnt work...
result = ''
for elem in root.findall('.//LEVEL1/DATA'):
mystr = elem.text.replace(" ","").replace("+","").replace("-","")
print mystr.replace(" ","").replace("+","").replace("-","")
我希望xml文件变量包含我的存储桶中文件的路径。或者找到一种解析文件内容的方法。
任何指出我正确方向的建议都表示赞赏。
干杯,克里斯
读取文件并解析它:
import cloudstorage as gcs
import xml.etree.ElementTree as ET
# The filename argument is specified in the format of YOUR_BUCKET_NAME/PATH_IN_GCS
gcs_file = gcs.open(filename)
contents = gcs_file.read()
gcs_file.close()
root = ET.fromstring(contents)