Python之XML,pythonxml

來源:互聯網
上載者:User

Python之XML,pythonxml

:Python有多種解析XML的方式,以下“ET”表示庫“ElementTree”(import xml.etree.ElementTree as ET)

1. et_tree = ET.parse('xxx.xml'):參數是一個流對象或檔案名稱,返回整個XML檔案的對象。

2. et_root = et_tree.getroot():擷取根節點,以下是以根節點et_root為例的節點用法。

  > len(et_root):直接子項目的個數;

  > for child_node in et_root:遍曆節點下的每一個直接子項目節點;

  > et_root.attrib:返回節點的屬性名稱和其值組成的字典;

  > et_root[3]:返回指定索引的直接子項目節點;

  > et_root.find(node_name):尋找節點下的第一個匹配到的直接子項目節點,若沒有此子節點或該節點根本沒有子節點時都會返回None;

  > et_root.findall(node_name):尋找節點下的所有直接子項目節點,若在節點名稱前面加上雙斜杠,則表示尋找該節點下的所有子項目,而不只是直接子項目,如:et_root.findall('//author'),表示尋找et_root節點下所有名為“author”的子節點;

  > et_root.text:返回節點的常值內容(若有的話);

3. 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.