簡體   English   中英

使用ElementTree解析XML-Python

[英]Using ElementTree to parse XML - python

我有一個XML文件,已經使用ElementTree解析了數據。 但是,我想解析數據並將其設置為等於變量,以便隨后將其輸出到.csv文件。

這是XML文件的摘錄:

<Item ID="productID" TableID="itemvp">
<ItemField TableFieldID="name" Value="totally awesome product"/>
<ItemField TableFieldID="code" Value="product code"/>
<ItemField TableFieldID="dimensions" Value="34&quot;W x 65&quot;D x 39&quot;H"/>
<ItemField TableFieldID="caption" Value="description"/>
<ItemField TableFieldID="upc" Value="upc code"/>
<ItemField TableFieldID="sale-price" Value="2599.95"/>
</Item>

這是我到目前為止的內容:

root = tree.getroot()
for child in root.iter('ItemField'):
    print child.attrib

這將以以下格式打印數據:

{'TableFieldID': 'name', 'Value': 'totally awesome product'}

基本上是字典。 我不知道如何解析它,以便可以將“ name”(非常棒的產品)的值設置為一個名為“ productName”的變量。 有關如何執行此操作的任何想法? 最終結果是將數據導出到.csv中。

在循環中,檢查TableFieldID是否為name ,然后將productName變量設置為Value

for child in root.iter('ItemField'):
    if child.attrib['TableFieldID'] == 'name':
        productName = child.attrib['Value']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM