使用Python解析Azure XML BLOB

2024-05-14 22:23:37 发布

您现在位置:Python中文网/ 问答频道 /正文

正在尝试解析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存储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的更好方法


Tags: nameimportparseasxmlblobetetree
1条回答
网友
1楼 · 发布于 2024-05-14 22:23:37

如果您想从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)

enter image description here

相关问题 更多 >

    热门问题