【问题标题】:Parse Azure XML BLOB using Python使用 Python 解析 Azure XML BLOB
【发布时间】:2020-08-24 10:01:35
【问题描述】:

尝试解析 XML BLOB 并将其转换为 CSV。使用本地文件时可以使用以下代码。

import xml.etree.ElementTree as et

SourceFileName = req.params.get('FileName')
SourceContainer = "C:\\AzureInputFiles\\"
SourceFileFullPath = SourceContainer + SourceFileName

xtree = et.parse(SourceFileFullPath)
xroot = xtree.findall(".//data/record") 
df_cols=['Col1', 'Col2']
rows = []

在 Azure BLOB 上工作时无法使用。我怎样才能做到这一点 ?不是最干净的,但通过创建带有参数的 URL 尝试了以下方式。容器设置为公共访问,并且 Blob 没有限制。 使用的库:azure-storage-blob

import xml.etree.ElementTree as et

url = f"https://{account_name}.blob.core.windows.net/{container_name}/{blob_name}"

xtree = et.parse(url)
xroot = xtree.findall(".//data/record") 
df_cols=['Col1', 'Col2']
rows = []

有什么建议让它工作吗?访问 Blob 的更好方法?

【问题讨论】:

    标签: python azure azure-functions azure-blob-storage


    【解决方案1】:

    如果你想从 Azure blob 中读取 xml 文件,我们可以使用包 azure.storage.blob 来实现它。

    例如

    我的 xml 文件

    <?xml version="1.0"?>
    <data>
        <country name="Liechtenstein">
            <rank>1</rank>
            <year>2008</year>
            <gdppc>141100</gdppc>
            <neighbor name="Austria" direction="E"/>
            <neighbor name="Switzerland" direction="W"/>
        </country>
        <country name="Singapore">
            <rank>4</rank>
            <year>2011</year>
            <gdppc>59900</gdppc>
            <neighbor name="Malaysia" direction="N"/>
        </country>
        <country name="Panama">
            <rank>68</rank>
            <year>2011</year>
            <gdppc>13600</gdppc>
            <neighbor name="Costa Rica" direction="W"/>
            <neighbor name="Colombia" direction="E"/>
        </country>
    </data>
    
    1. 代码
    import xml.etree.ElementTree as ET
    
    from azure.storage.blob import BlobServiceClient
    
    connection_string='<your storage account connection string>'
    blob_service_client = BlobServiceClient.from_connection_string(connection_string)
    
    blob_client = blob_service_client.get_blob_client(container="test", blob="data.xml")
    downloader = blob_client.download_blob()
    root = ET.fromstring(downloader.content_as_text())
    for neighbor in root.iter('neighbor'):
        print(neighbor.attrib)
    

    【讨论】:

    • 谢谢吉姆。通过一些修改,我能够得到预期的结果。
    猜你喜欢
    • 1970-01-01
    • 2021-02-06
    • 2017-08-31
    • 2014-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多