0
我有一個XML文件,我已經用ElementTree解析出數據。但是,我想分析數據並將其設置爲等於一個變量,然後我可以將其輸出到.csv文件。使用ElementTree解析XML -python
下面是XML文件的snipet:
<Item ID="productID" TableID="itemvp">
<ItemField TableFieldID="name" Value="totally awesome product"/>
<ItemField TableFieldID="code" Value="product code"/>
<ItemField TableFieldID="dimensions" Value="34"W x 65"D x 39"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格式導出這些數據。
如果我想設置成變量幾個不同的價值觀,我會,如果執行全部通過聲明?如下所示: 如果child.attrib ['TableFieldID'] =='code',則爲root.iter('ItemField')中的child的root = tree.getroot() : productCode = child.attrib ['Value '] if child.attrib ['TableFieldID'] =='name': productName = child.attrib ['Value']' – Bokai
您也可以使用XPath語法來查找所需的元素:https:// docs。 python.org/3/library/xml.etree.elementtree.html#xpath-support – dvnguyen
太棒了!謝謝你給我看。 – Bokai