【问题标题】:Using ElementTree to parse XML - python使用 ElementTree 解析 XML - python
【发布时间】:2016-11-17 03:32:20
【问题描述】:

我有一个 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 格式导出此数据。

【问题讨论】:

    标签: python xml elementtree


    【解决方案1】:

    在您的循环中,检查TableFieldID 是否为name,然后将productName 变量设置为Value

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

    【讨论】:

    • 如果我想为变量设置几个不同的值,我必须通过 if 语句来运行它们吗?像这样: root = tree.getroot() for child in root.iter('ItemField'): if child.attrib['TableFieldID'] == 'code': productCode = child.attrib['Value'] if child. attrib['TableFieldID'] == 'name': productName = child.attrib['Value']'
    • 您还可以使用 XPath 语法来定位所需的元素:docs.python.org/3/library/…
    猜你喜欢
    • 2021-02-06
    • 2017-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多