【发布时间】:2018-08-01 06:46:44
【问题描述】:
我想在此处为该元素 country singapore 旁边的元素创建子元素。
假设我的 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")
我可以将子元素添加到国家元素。但是我不能在国家“新加坡”下面使用地区元素。
有人可以帮我吗?
【问题讨论】:
-
您能否将预期的输出 xml 发布到问题中
-
所以你想编辑
district元素,它最近的前兄弟是新加坡的country元素?你能用 lxml 代替 ElementTree 吗? lxml 中的 XPath 支持要好得多。 -
不,我不能使用 lxml
标签: python xpath elementtree