gpt4 book ai didi

python - ElementTree - 将子元素附加到元素时出现问题

转载 作者:行者123 更新时间:2023-12-01 09:11:25 25 4
gpt4 key购买 nike

我想为此处元素国家/地区新加坡旁边的元素创建子元素。

假设我的 test.xml 文件如下所示

<?xml version="1.0" encoding="UTF-8"?>

<data>
<country name="Malaysia" tst="bh">
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Singapore" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<district>
<A name="test">
</A>
</district>
<country name="Singapore" tst="ab">
<rank updated="yes">5</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<district>
<B name="test">
</B>
</district>
</data>

在上面的示例中,我想为元素区创建子元素,但上面显示的元素应该是国家/地区“新加坡”。应该是

<district>
<t1 name="t1>
</t1>
<B name="test">
</B>
</district>

import xml.etree.ElementTree as et


tree = et.parse("test.xml")
root = tree.getroot()

country = root.find(".//country[@name='Singapore']")

et.subelement(country,"add new subelement")

我可以将子元素添加到国家/地区元素中。但我无法将地区元素置于国家“新加坡”之下。

有人可以帮我吗?

最佳答案

以下是如何使用 ElementTree 完成此操作。

import xml.etree.ElementTree as ET

root = ET.parse("country.xml").getroot()

# A list of all children of the root element (in document order)
children = list(root)

# Find the Singapore 'country' element
sing = root.find(".//country/[@name='Singapore']")

# Get the index of the 'country' element
ix = children.index(sing)

# Find the wanted 'district' sibling element (position ix+1 in the list)
district = children[ix+1]

# Create a new 't1' element and add to 'district'
t1 = ET.Element("t1", name="t1")
district.insert(0, t1)

print(ET.tostring(root).decode("UTF-8"))

输出:

<data>
<country name="Malaysia" tst="bh">
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor direction="E" name="Singapore" />
<neighbor direction="W" name="Switzerland" />
</country>
<district>
<A name="test">
</A>
</district>
<country name="Singapore" tst="ab">
<rank updated="yes">5</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor direction="N" name="Malaysia" />
</country>
<district>
<t1 name="t1" /><B name="test"> <!-- New element added here -->
</B>
</district>
</data>

关于python - ElementTree - 将子元素附加到元素时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51626950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com