使用Python删除XML文件中的元素

时间:2017-12-27 09:07:19

标签: python xml

我是Python的新手,我想从XML中删除元素openingHours和子元素。

我有这个输入

<Root>
   <stations>
      <station id= "1">
          <name>whatever</name>
          <openingHours>
               <openingHour>
                    <entrance>main</entrance>
                       <timeInterval>
                         <from>05:30</from>
                         <to>21:30</to>
                       </timeInterval>
                <openingHour/>
          <openingHours>
      <station/>
      <station id= "2">
          <name>foo</name>
          <openingHours>
               <openingHour>
                    <entrance>main</entrance>
                       <timeInterval>
                         <from>06:30</from>
                         <to>21:30</to>
                       </timeInterval>
                <openingHour/>
          <openingHours>
       <station/>
   <stations/>
  <Root/>

我想要这个输出

  <Root>
   <stations>
      <station id= "1">
          <name>whatever</name>
      <station/>
      <station id= "2">
          <name>foo</name>
      <station/>
   <stations/>
  <Root/>

到目前为止,我已经从另一个帖子How to remove elements from XML using Python

尝试了这个
from lxml import etree

doc=etree.parse('stations.xml')
for elem in doc.xpath('//*[attribute::openingHour]'):
   parent = elem.getparent()
   parent.remove(elem)
print(etree.tostring(doc))

然而,它似乎没有起作用。 感谢

2 个答案:

答案 0 :(得分:1)

我把你的代码转了一下,但起初Python并不同意你编写XML的方式,希望结束标记中的/位于开头(如</...>而不是在最后(<.../>)。

除此之外,您的代码无法正常工作的原因是因为xpath表达式正在寻找属性 openingHour,而实际上您想要查找名为openingHours元素。我通过将表达式更改为//openingHours来实现它。制作完整的代码:

from lxml import etree

doc=etree.parse('stations.xml')
for elem in doc.xpath('//openingHours'):
    parent = elem.getparent()
    parent.remove(elem)
print(etree.tostring(doc))

答案 1 :(得分:0)

您要删除标记<openingHours>而不删除名称为openingHour的某些属性:

from lxml import etree

doc = etree.parse('stations.xml')
for elem in doc.findall('.//openingHours'):
    parent = elem.getparent()
    parent.remove(elem)
print(etree.tostring(doc))