Python仅重命名xml中许多节点中的第一个

时间:2018-09-20 13:42:02

标签: xml python-3.x

im正在研究从REST API获取xml文件的python解决方案。虽然我可以轻松地从软件映射常规字段,但是它们的自定义字段需要一些工作。

此刻我困扰的问题是xml文件看起来像这样。

    <Label>zip</Label>
    <Value>6230</Value>
    <Label>city</Label>
    <Value>Rødekro</Value>
    <Label>country</Label>
    <Value>Danmark</Value>
    <Label>date</Label>
    <Value>09/20/2018</Value>

下面是我需要的。

    <zip>6230</zip>
    <city>Rødekro</city>
    <country>Danmark</country>
    <date>09/20/2018</date>

有没有一种方法可以选择各个值节点并以某种方式重命名它们?

解决方案中问题的示例,请阅读全文的评论。

    <a>
    <b>
    <Label>zip</Label>
    <Value>6230</Value>
    <Label>city</Label>
    <Value>Rødekro</Value>
    <Label>country</Label>
    <Value>Danmark</Value>
    <c>something</c>
    <Label>date</Label>
    <Value>09/20/2018</Value>
    </b>
    </a>

2 个答案:

答案 0 :(得分:2)

您可以使用ElementTree迭代器来移动节点。

import xml.etree.ElementTree as ET

tree = ET.parse('temp.xml')
root = tree.getroot()
new_root = ET.Element('address')

it = root.iter()
next(it)
for x in it:
    # skip nodes here or you can add to tree as it is.
    if x.tag != 'Label':
       continue
    child = ET.SubElement(new_root, x.text)
    child.text = next(it).text

print(ET.tostring(new_root))

我使用了这个'temp.xml'

<address>
    <Label>zip</Label>
    <Value>6230</Value>
    <Label>city</Label>
    <Value>Rødekro</Value>
    <Label>country</Label>
    <Value>Danmark</Value>
    <c>NOT NEED</c>
    <Label>date</Label>
    <Value>09/20/2018</Value>
</address>

答案 1 :(得分:0)

您可以使用XSLT(可扩展样式表语言转换)来转换XML文件。 lxml库是适用于此目的的众所周知的库。由于您的节点没有特定的名称,因此您必须依靠节点内容(例如 zip country )并从下一个节点获取相关值( Value )。