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