第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

剝離lxml中的單個元素

剝離lxml中的單個元素

Cats萌萌 2022-11-01 14:33:46
我需要在保留其數(shù)據(jù)的同時刪除 XML 元素。lxml 函數(shù)strip_tags確實刪除了元素,但它以遞歸方式工作,我想去除單個元素。我嘗試使用這篇文章的答案,但remove刪除了整個元素。xml="""<groceries>  One <fruit state="rotten">apple</fruit> a day keeps the doctor away.  This <fruit state="fresh">pear</fruit> is fresh.</groceries>"""tree=ET.fromstring(xml)for bad in tree.xpath("//fruit[@state='rotten']"):    bad.getparent().remove(bad)print (ET.tostring(tree, pretty_print=True))我想得到<groceries>    One apple a day keeps the doctor away.    This <fruit state="fresh">pear</fruit> is fresh.</groceries>\n'我明白了<groceries>    This <fruit state="fresh">pear</fruit> is fresh.</groceries>\n'我嘗試使用strip_tags:for bad in tree.xpath("//fruit[@state='rotten']"):    ET.strip_tags(bad.getparent(), bad.tag)<groceries>    One apple a day keeps the doctor away.    This pear is fresh.</groceries>但這會剝離一切,我只想用state='rotten'.
查看完整描述

1 回答

?
ibeautiful

TA貢獻(xiàn)1993條經(jīng)驗 獲得超6個贊

也許其他人有更好的主意,但這是一種可能的解決方法:


bad = tree.xpath(".//fruit[@state='rotten']")[0] #for simplicity, I didn't bother with a for loop in this case

txt = bad.text+bad.tail # collect the text content of bad; strangely enough it's not just 'apple'

bad.getparent().text += txt # add the collected text to the parent's existing text

tree.remove(bad) # this gets rid only of this specific 'bad'

print(etree.tostring(tree).decode())

輸出:


<groceries>

  One apple a day keeps the doctor away.

  This <fruit state="fresh">pear</fruit> is fresh.

</groceries>


查看完整回答
反對 回復(fù) 2022-11-01
  • 1 回答
  • 0 關(guān)注
  • 101 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號