2017-12-27 21 views
0

私はPythonの初心者ですが、XMLから要素openingHoursと子要素を削除したいと思います。Pythonを使ってXMLファイルの要素を削除する

私は私がこれまでのところ、私は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)) 

別のスレッドからこれを試してみたが、それはdoesnのこの出力

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

をたいと思い、この入力

<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/> 

を持っています働いているようだ。あなたが名前openingHourでタグ<openingHours>ではなく、いくつかの属性を削除したい おかげ

答えて

1

はあなたのXMLを構成方法に同意することができませんでした終了タグの/が末尾(<.../>)でなく、先頭(たとえば</...>)になるようにします。現実には、あなたがopeningHoursと呼ば要素を探したいながらxpath式が属性openingHourを探しているのでさておき、あなたのコードが動作しない理由がある

。私は式を//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)) 
0

:私はスピンのためではなく、最初のPythonであなたのコードを取った

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)) 
関連する問題