python簡單處理xml檔案

來源:互聯網
上載者:User

標籤:clear   code   col   component   set   color   lxml   等等   debug   

Python若是想從xml裡讀點資訊,用BeautifulSoup可能會容易一點,但是如果要修改xml,BeatifulSoup就搞不定了,其實直接用lxml就好。

1 from lxml import etree2 3 tree = etree.parse("xxx.xml")4 cfgs = tree.find(‘//component[@name="cmake-settings"]/configurations‘)5 cfgs.clear()6 cfgs.append(etree.Element("configuration", attrib={"CONFIG_NAME":"Debug"}))7 tree.write("xxx.xml")

 etree表示整個xml樹結構,對其元素修改,就直接表現為對etree的修改,然後儲存即可。一般的函數用法現查即可,只有XPath需要瞭解下。目前我只瞭解了以一下幾項,基本夠用:

  • /:表示類似路徑中的/,表示下一級
  • //:表示後代,即下一級、下兩級、等等等……
  • [@<attr-name>=<attr-val>]:可以根據屬性值來過濾
  • *:表示匹配所有,例如://*表示所有的後代

 

 

 

 

python簡單處理xml檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.