PythonのxmlモジュールのElementTreeのルート要素を取得する
PythonのxmlまたはdefusedxmlモジュールのElementTreeオブジェクトのルート要素を、Elementオブジェクトとして取得します。
目次
getrootメソッドでルートを取得する
ElementTreeオブジェクトのgetrootメソッドで、根要素のElementオブジェクトを取得できます。
import defusedxml.ElementTree as ET
# import xml.etree.ElementTree as ET # 組み込みのxmlモジュールを使う場合
root = tree.getroot()
| 変数 | 型 | 内容 | 
|---|---|---|
| tree | ElementTree | 元のElementTreeオブジェクト。 | 
| root | Element | ElementTreeの根要素。 | 
defusedxmlモジュール は、xmlモジュールと使い方の互換性を保ちつつ、XMLの脆弱性に対処したモジュールです。
実施例
試してみましょう。
下記のXMLファイルをElementTreeとして読み込んで、ルートの子の要素のタグ名と属性を出力します。
<?xml version="1.0" encoding="UTF-8" ?>
<tip>
    <middle id='1'>
        <bottom>content_1</bottom>
    </middle>
    <middle id='2'>
        <!--
        <bottom>content_20</bottom>
        <bottom>content_21</bottom>
        -->
        <bottom>いろは</bottom>
        <bottom>にほへと</bottom>
        <bottom></bottom>
    </middle>
    <middle id='3'>
        content_3
    </middle>
</tip>
import defusedxml.ElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()
for i in root:
    print(i.tag, i.attrib)
出力はこうなります。
middle {'id': '1'}
middle {'id': '2'}
middle {'id': '3'}
正しく出力されました。
公開日
広告
PythonとXMLカテゴリの投稿
- PythonでHTMLから特定のタグを抜き出してCSVにする
- PythonでHTMLを加工する
- PythonでXMLと文字列の変換
- PythonでXMLの構造を表示してみた
- PythonでXMLの読み込みと書き出し
- PythonのBeautifulSoup4でHTMLに要素を追加する
- PythonのBeautifulSoup4でHTMLの要素の内容にアクセスする
- PythonのBeautifulSoup4でHTMLの要素の内容を削除する
- PythonのBeautifulSoup4でHTMLの要素の囲いを外す
- PythonのBeautifulSoup4でHTMLの要素を削除する
- PythonのBeautifulSoup4でHTMLの要素を抜き出す
- PythonのBeautifulSoup4でHTMLの要素を新しい要素で囲う
- PythonのBeautifulSoup4でHTMLの要素を検索する
- Pythonのxmlで要素を列挙する
- PythonのxmlモジュールのElementTreeのルート要素を取得する
- PythonのxmlモジュールのElementからElementTreeを作る