xml.etree.ElementTree --- ElementTree XML API

Source code: Lib/xml/etree/ElementTree.py


xml.etree.ElementTree モジュールは、XML データを解析および作成するシンプルかつ効率的な API を実装しています。

バージョン 3.3 で変更: このモジュールは利用出来る場合は常に高速な実装を使用します。

バージョン 3.3 で非推奨: The xml.etree.cElementTree module is deprecated.

警告

xml.etree.ElementTree モジュールは悪意を持って作成されたデータに対して安全ではありません。信頼できないデータや認証されていないデータをパースする必要がある場合は XML の脆弱性 を参照してください。

チュートリアル

これは xml.etree.ElementTree (略して ET) を使用するための短いチュートリアルで、ブロックの構築およびモジュールの基本コンセプトを紹介することを目的としています。

XML 木構造と要素

XML は本質的に階層データ形式で、木構造で表すのが最も自然な方法です。ET はこの目的のために 2 つのクラス - XML 文書全体を木で表す ElementTree および木構造内の単一ノードを表す Element - を持っています。文書全体とのやりとり (ファイルの読み書き) は通常 ElementTree レベルで行います。単一 XML 要素およびその子要素とのやりとりは Element レベルで行います。

XML の解析

このセクションでは例として以下の XML 文書を使います:

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

ファイルを読み込むことでこのデータをインポートすることが出来ます:

import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()

文字列から直接インポートすることも出来ます:

root = ET.fromstring(country_data_as_string)

fromstring() は XML を文字列から Element に直接パースします。Element はパースされた木のルート要素です。他のパース関数は ElementTree を作成するかもしれません。ドキュメントをきちんと確認してください。

Element として、root はタグと属性の辞書を持ちます:

>>> root.tag
'data'
>>> root.attrib
{}

さらにイテレート可能な子ノードも持ちます:

>>> for child in root:
...     print(child.tag, child.attrib)
...
country {'name': 'Liechtenstein'}
country {'name': 'Singapore'}
country {'name': 'Panama'}

子ノードは入れ子になっており、インデックスで子ノードを指定してアクセスできます:

>>> root[0][1].text
'2008'

注釈

XML 入力の全ての要素が、パース後の木に要素として含まれる訳ではありません。現在、このモジュールは入力中のいかなる XML コメント、処理命令、ドキュメントタイプ宣言も読み飛ばします。しかし、XML テキストからのパースではなく、このモジュールの API を使用して構築された木には、コメントや処理命令を含むことができ、それらは XML 出力の生成時に含まれます。ドキュメントタイプ宣言は、 XMLParser コンストラクタにカスタムの TreeBuilder インスタンスを渡すことで、アクセスすることができます。

非ブロックパースのためのプル API

このモジュールが提供するパース関数のほとんどは、結果を返す前に、ドキュメント全体を読む必要があります。 XMLParser を使用して、インクリメンタルにデータを渡すことは可能ではありますが、それはコールバック対象のメソッドを呼ぶプッシュ API であり、多くの場合、低水準すぎて不便です。ユーザーが望むのは、完全に出来上がった Element オブジェクトを便利に使いながら、操作をブロックすることなく XML のパースをインクリメンタルに行えることです。

これを行うための最も強力なツールは、 XMLPullParser です。XML データを取得するためにブロックするような読み込みは必要なく、 XMLPullParser.feed() を呼び出して、インクリメンタルにデータを読みます。パースされた XML 要素を取得するには、XMLPullParser.read_events() を呼び出します。以下に、例を示します。

>>> parser = ET.XMLPullParser(['start', 'end'])
>>> parser.feed('<mytag>sometext')
>>> list(parser.read_events())
[('start', <Element 'mytag' at 0x7fa66db2be58>)]
>>> parser.feed(' more text</mytag>')
>>> for event, elem in parser.read_events():
...     print(event)
...     print(elem.tag, 'text=', elem.text)
...
end
mytag text= sometext more text

これの分かりやすい用途は、XML データをソケットから受信したり、ストレージデバイスからインクリメンタルに読み出したりするような、非ブロック式に動作するアプリケーションです。このような場合、ブロッキング読み出しは使用できません。

XMLPullParser は柔軟性が非常に高いため、単純に使用したいユーザーにとっては不便かもしれません。アプリケーションにおいて、XML データの読み取り時にブロックすることに支障がないが、インクリメンタルにパースする能力が欲しい場合、iterparse() を参照してください。大きな XML ドキュメントを読んでいて、全てメモリ上にあるという状態にしたくない場合に有用です。

Where immediate feedback through events is wanted, calling method XMLPullParser.flush() can help reduce delay; please make sure to study the related security notes.

関心ある要素の検索

Element は、例えば、Element.iter() などの、配下 (その子ノードや孫ノードなど) の部分木全体を再帰的にイテレートするいくつかの役立つメソッドを持っています:

>>> for neighbor in root.iter('neighbor'):
...     print(neighbor.attrib)
...
{'name': 'Austria', 'direction': 'E'}
{'name': 'Switzerland', 'direction': 'W'}
{'name': 'Malaysia', 'direction': 'N'}
{'name': 'Costa Rica', 'direction': 'W'}
{'name': 'Colombia', 'direction': 'E'}

Element.findall() はタグで現在の要素の直接の子要素のみ検索します。 Element.find() は特定のタグで 最初の 子要素を検索し、 Element.text は要素のテキストコンテンツにアクセスします。 Element.get() は要素の属性にアクセスします:

>>> for country in root.findall('country'):
...     rank = country.find('rank').text
...     name = country.get('name')
...     print(name, rank)
...
Liechtenstein 1
Singapore 4
Panama 68

XPath を使用すると、より洗練された方法で、検索したい要素を指定することができます。

XML ファイルの編集

ElementTree は XML 文書を構築してファイルに出力する簡単な方法を提供しています。ElementTree.write() メソッドはこの目的に適います。

Element オブジェクトを作成すると、そのフィールドの直接変更 (Element.text など) や、属性の追加および変更 (Element.set() メソッド)、あるいは新しい子ノードの追加 (例えば Element.append() など) によってそれを操作できます。

例えば各 country の rank に 1 を足して、rank 要素に updated 属性を追加したい場合:

>>> for rank in root.iter('rank'):
...     new_rank = int(rank.text) + 1
...     rank.text = str(new_rank)
...     rank.set('updated', 'yes')
...
>>> tree.write('output.xml')

XML はこのようになります:

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

Element.remove() を使って要素を削除することが出来ます。例えば rank が 50 より大きい全ての country を削除したい場合:

>>> for country in root.findall('country'):
...     # using root.findall() to avoid removal during traversal
...     rank = int(country.find('rank').text)
...     if rank > 50:
...         root.remove(country)
...
>>> tree.write('output.xml')

Note that concurrent modification while iterating can lead to problems, just like when iterating and modifying Python lists or dicts. Therefore, the example first collects all matching elements with root.findall(), and only then iterates over the list of matches.

XML はこのようになります:

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
</data>

XML 文書の構築

SubElement() 関数は、与えられた要素に新しい子要素を作成する便利な手段も提供しています:

>>> a = ET.Element('a')
>>> b = ET.SubElement(a, 'b')
>>> c = ET.SubElement(a, 'c')
>>> d = ET.SubElement(c, 'd')
>>> ET.dump(a)
<a><b /><c><d /></c></a>

名前空間のある XML の解析

XML 入力が 名前空間 を持っている場合、 prefix:sometag の形式で修飾されたタグと属性が、その prefix が完全な URI で置換された {uri}sometag の形に展開されます。さらに、 デフォルトの XML 名前空間 があると、修飾されていない全てのタグにその完全 URI が前置されます。

ひとつは接頭辞 "fictional" でもうひとつがデフォルト名前空間で提供された、 2 つの名前空間を組み込んだ XML の例をここにお見せします:

<?xml version="1.0"?>
<actors xmlns:fictional="http://characters.example.com"
        xmlns="http://people.example.com">
    <actor>
        <name>John Cleese</name>
        <fictional:character>Lancelot</fictional:character>
        <fictional:character>Archie Leach</fictional:character>
    </actor>
    <actor>
        <name>Eric Idle</name>
        <fictional:character>Sir Robin</fictional:character>
        <fictional:character>Gunther</fictional:character>
        <fictional:character>Commander Clement</fictional:character>
    </actor>
</actors>

この XML の例を、検索し、渡り歩くためのひとつの方法としては、 find()findall() に渡す xpath で全てのタグや属性に手作業で URI を付けてまわる手があります:

root = fromstring(xml_text)
for actor in root.findall('{http://people.example.com}actor'):
    name = actor.find('{http://people.example.com}name')
    print(name.text)
    for char in actor.findall('{http://characters.example.com}character'):
        print(' |-->', char.text)

もっと良い方法があります。接頭辞の辞書を作り、これを検索関数で使うことです:

ns = {'real_person': 'http://people.example.com',
      'role': 'http://characters.example.com'}

for actor in root.findall('real_person:actor', ns):
    name = actor.find('real_person:name', ns)
    print(name.text)
    for char in actor.findall('role:character', ns):
        print(' |-->', char.text)

どちらのアプローチでも同じ結果です:

John Cleese
 |--> Lancelot
 |--> Archie Leach
Eric Idle
 |--> Sir Robin
 |--> Gunther
 |--> Commander Clement

XPath サポート

このモジュールは木構造内の要素の位置決めのための XPath 式 を限定的にサポートしています。その目指すところは短縮構文のほんの一部だけのサポートであり、XPath エンジンのフルセットは想定していません。

使用例

以下はこのモジュールの XPath 機能の一部を紹介する例です。XML の解析 節から XML 文書 countrydata を使用します:

import xml.etree.ElementTree as ET

root = ET.fromstring(countrydata)

# Top-level elements
root.findall(".")

# All 'neighbor' grand-children of 'country' children of the top-level
# elements
root.findall("./country/neighbor")

# Nodes with name='Singapore' that have a 'year' child
root.findall(".//year/..[@name='Singapore']")

# 'year' nodes that are children of nodes with name='Singapore'
root.findall(".//*[@name='Singapore']/year")

# All 'neighbor' nodes that are the second child of their parent
root.findall(".//neighbor[2]")

For XML with namespaces, use the usual qualified {namespace}tag notation:

# All dublin-core "title" tags in the document
root.findall(".//{http://purl.org/dc/elements/1.1/}title")

サポートされている XPath 構文

操作

意味

tag

Selects all child elements with the given tag. For example, spam selects all child elements named spam, and spam/egg selects all grandchildren named egg in all children named spam. {namespace}* selects all tags in the given namespace, {*}spam selects tags named spam in any (or no) namespace, and {}* only selects tags that are not in a namespace.

バージョン 3.8 で変更: Support for star-wildcards was added.

*

Selects all child elements, including comments and processing instructions. For example, */egg selects all grandchildren named egg.

.

現在のノードを選択します。これはパスの先頭に置くことで相対パスであることを示すのに役立ちます。

//

現在の要素の下にある全てのレベルの全ての子要素を選択します。例えば、.//egg は木全体から egg 要素を選択します。

..

親ノードを選択します。パスが開始要素 (find が呼ばれた要素) の上の要素に進もうとした場合 None を返します。

[@attrib]

与えられた属性を持つ全ての要素を選択します。

[@attrib='value']

与えられた属性が与えられた値を持つ全ての要素を選択します。 値に引用符は含められません。

[@attrib!='value']

Selects all elements for which the given attribute does not have the given value. The value cannot contain quotes.

バージョン 3.10 で追加.

[tag]

tag という名前の子要素を持つ全ての要素を選択します。 直下の子要素のみサポートしています。

[.='text']

子孫のうち、与えられた text とテキスト全体が等しい全ての要素を選択します。

バージョン 3.7 で追加.

[.!='text']

Selects all elements whose complete text content, including descendants, does not equal the given text.

バージョン 3.10 で追加.

[tag='text']

子孫を含む完全なテキストコンテンツと与えられた text が一致する、 tag と名付けられた子要素を持つすべての要素を選択します。

[tag!='text']

Selects all elements that have a child named tag whose complete text content, including descendants, does not equal the given text.

バージョン 3.10 で追加.

[position]

与えられた位置にあるすべての要素を選択します。位置は整数 (先頭は 1)、式 last() (末尾)、あるいは末尾からの相対位置 (例えば last()-1) のいずれかで指定できます。

述語 (角括弧内の式) の前にはタグ名、アスタリスク、あるいはその他の述語がなければなりません。 position 述語の前にはタグ名がなければなりません。

リファレンス

関数

xml.etree.ElementTree.canonicalize(xml_data=None, *, out=None, from_file=None, **options)

C14N 2.0 transformation function.

Canonicalization is a way to normalise XML output in a way that allows byte-by-byte comparisons and digital signatures. It reduced the freedom that XML serializers have and instead generates a more constrained XML representation. The main restrictions regard the placement of namespace declarations, the ordering of attributes, and ignorable whitespace.

This function takes an XML data string (xml_data) or a file path or file-like object (from_file) as input, converts it to the canonical form, and writes it out using the out file(-like) object, if provided, or returns it as a text string if not. The output file receives text, not bytes. It should therefore be opened in text mode with utf-8 encoding.

Typical uses:

xml_data = "<root>...</root>"
print(canonicalize(xml_data))

with open("c14n_output.xml", mode='w', encoding='utf-8') as out_file:
    canonicalize(xml_data, out=out_file)

with open("c14n_output.xml", mode='w', encoding='utf-8') as out_file:
    canonicalize(from_file="inputfile.xml", out=out_file)

The configuration options are as follows:

  • with_comments: set to true to include comments (default: false)

  • strip_text: set to true to strip whitespace before and after text content

    (default: false)

  • rewrite_prefixes: set to true to replace namespace prefixes by "n{number}"

    (default: false)

  • qname_aware_tags: a set of qname aware tag names in which prefixes

    should be replaced in text content (default: empty)

  • qname_aware_attrs: a set of qname aware attribute names in which prefixes

    should be replaced in text content (default: empty)

  • exclude_attrs: a set of attribute names that should not be serialised

  • exclude_tags: a set of tag names that should not be serialised

In the option list above, "a set" refers to any collection or iterable of strings, no ordering is expected.

バージョン 3.8 で追加.

xml.etree.ElementTree.Comment(text=None)

コメント要素のファクトリです。このファクトリ関数は、標準のシリアライザでは XML コメントにシリアライズされる特別な要素を作ります。コメント文字列はバイト文字列でも Unicode 文字列でも構いません。text はそのコメント文字列を含んだ文字列です。コメントを表わす要素のインスタンスを返します。

XMLParser は、入力に含まれるコメントを読み飛ばし、コメントオブジェクトは作成しません。ElementTree は、Element メソッドの 1 つを使用して木内に挿入されたコメントノードのみを含みます。

xml.etree.ElementTree.dump(elem)

要素の木もしくは要素の構造を sys.stdout に出力します。この関数はデバッグ目的のみに使用してください。

出力される形式の正確なところは実装依存です。このバージョンでは、通常の XML ファイルとして出力されます。

elem は要素の木もしくは個別の要素です。

バージョン 3.8 で変更: The dump() function now preserves the attribute order specified by the user.

xml.etree.ElementTree.fromstring(text, parser=None)

文字列定数で与えられた XML 断片を解析します。 XML() と同じです。 text には XML データを含む文字列を指定します。 parser はオプションで、パーザのインスタンスを指定します。指定されなかった場合、標準の XMLParser パーザを使用します。 Element インスタンスを返します。

xml.etree.ElementTree.fromstringlist(sequence, parser=None)

文字列フラグメントのシーケンスから XML ドキュメントを解析します。 sequence は XML データのフラグメントを格納した、リストかその他のシーケンスです。 parser はオプションのパーザインスタンスです。パーザが指定されない場合、標準の XMLParser パーザが使用されます。 Element インスタンスを返します。

バージョン 3.2 で追加.

xml.etree.ElementTree.indent(tree, space='  ', level=0)

Appends whitespace to the subtree to indent the tree visually. This can be used to generate pretty-printed XML output. tree can be an Element or ElementTree. space is the whitespace string that will be inserted for each indentation level, two space characters by default. For indenting partial subtrees inside of an already indented tree, pass the initial indentation level as level.

バージョン 3.9 で追加.

xml.etree.ElementTree.iselement(element)

オブジェクトが正当な要素オブジェクトであるかをチェックします。 element は要素インスタンスです。引数が要素オブジェクトの場合 True を返します。

xml.etree.ElementTree.iterparse(source, events=None, parser=None)

Parses an XML section into an element tree incrementally, and reports what's going on to the user. source is a filename or file object containing XML data. events is a sequence of events to report back. The supported events are the strings "start", "end", "comment", "pi", "start-ns" and "end-ns" (the "ns" events are used to get detailed namespace information). If events is omitted, only "end" events are reported. parser is an optional parser instance. If not given, the standard XMLParser parser is used. parser must be a subclass of XMLParser and can only use the default TreeBuilder as a target. Returns an iterator providing (event, elem) pairs; it has a root attribute that references the root element of the resulting XML tree once source is fully read. The iterator has the close() method that closes the internal file object if source is a filename.

iterparse() は木をインクリメンタルに構築しますが、source (または指定のファイル) でのブロッキング読みを起こします。したがって、ブロッキング読みが許可されないアプリケーションには適しません。完全に非ブロックのパースのためには、XMLPullParser を参照してください。

注釈

iterparse() は "start" イベントを発行した時に開始タグの文字 ">" が現れたことだけを保証します。そのため、属性は定義されますが、その時点ではテキストの内容も tail 属性も定義されていません。同じことは子要素にも言えて、その時点ではあるともないとも言えません。

全部揃った要素が必要ならば、"end" イベントを探してください。

バージョン 3.4 で非推奨: parser 引数。

バージョン 3.8 で変更: イベント comment, pi が追加されました。

バージョン 3.13 で変更: Added the close() method.

xml.etree.ElementTree.parse(source, parser=None)

XML 断片を解析して要素の木にします。 source には XML データを含むファイル名またはファイルオブジェクトを指定します。 parser はオプションでパーザインスタンスを指定します。パーザが指定されない場合、標準の XMLParser パーザが使用されます。 ElementTree インスタンスを返します。

xml.etree.ElementTree.ProcessingInstruction(target, text=None)

PI 要素のファクトリです。このファクトリ関数は XML の処理命令としてシリアライズされた特別な要素を作成します。target は PI ターゲットを含んだ文字列です。text を指定する場合は PI コンテンツを含む文字列にします。PI を表わす要素インスタンスを返します。

Note that XMLParser skips over processing instructions in the input instead of creating PI objects for them. An ElementTree will only contain processing instruction nodes if they have been inserted into to the tree using one of the Element methods.

xml.etree.ElementTree.register_namespace(prefix, uri)

名前空間の接頭辞を登録します。レジストリはグローバルで、与えられた接頭辞か名前空間 URI のどちらかの既存のマッピングはすべて削除されます。prefix には名前空間の接頭辞を指定します。uri には名前空間の URI を指定します。この名前空間のタグや属性は、可能な限り与えられた接頭辞をつけてシリアライズされます。

バージョン 3.2 で追加.

xml.etree.ElementTree.SubElement(parent, tag, attrib={}, **extra)

子要素のファクトリです。この関数は要素インスタンスを作成し、それを既存の要素に追加します。

要素名、属性名、および属性値はバイト文字列でも Unicode 文字列でも構いません。 parent には親要素を指定します。 tag には要素名を指定します。attrib はオプションで要素の属性を含む辞書を指定します。 extra は追加の属性で、キーワード引数として与えます。要素インスタンスを返します。

xml.etree.ElementTree.tostring(element, encoding='us-ascii', method='xml', *, xml_declaration=None, default_namespace=None, short_empty_elements=True)

XML 要素を全ての子要素を含めて表現する文字列を生成します。 elementElement のインスタンスです。 encoding [1] は出力エンコーディング(デフォルトは US-ASCII)です。Unicode 文字列を生成するには、encoding="unicode" を使用してください。 method"xml", "html", "text" のいずれか(デフォルトは "xml") です。 xml_declaration, default_namespace, short_empty_elements は、 ElementTree.write() での意味と同じ意味を持ちます。 XML データを含んだ (オプションで) エンコードされた文字列を返します。

バージョン 3.4 で変更: Added the short_empty_elements parameter.

バージョン 3.8 で変更: Added the xml_declaration and default_namespace parameters.

バージョン 3.8 で変更: The tostring() function now preserves the attribute order specified by the user.

xml.etree.ElementTree.tostringlist(element, encoding='us-ascii', method='xml', *, xml_declaration=None, default_namespace=None, short_empty_elements=True)

XML 要素を全ての子要素を含めて表現する文字列を生成します。 elementElement のインスタンスです。 encoding [1] は出力エンコーディング(デフォルトは US-ASCII)です。Unicode 文字列を生成するには、encoding="unicode" を使用してください。 method"xml", "html", "text" のいずれか(デフォルトは "xml") です。 xml_declaration*, default_namespace, short_empty_elements は、 ElementTree.write() での意味と同じ意味を持ちます。 XML データを含んだ (オプションで) エンコードされた文字列のリストを返します。b"".join(tostringlist(element)) == tostring(element) となること以外、特定の順序になる保証はありません。

バージョン 3.2 で追加.

バージョン 3.4 で変更: Added the short_empty_elements parameter.

バージョン 3.8 で変更: Added the xml_declaration and default_namespace parameters.

バージョン 3.8 で変更: tostringlist() 関数はユーザーが指定した属性の順序を保持するようになりました。

xml.etree.ElementTree.XML(text, parser=None)

文字列定数で与えられた XML 断片を解析します。この関数は Python コードに "XML リテラル" を埋め込むのに使えます。 text には XML データを含む文字列を指定します。 parser はオプションで、パーザのインスタンスを指定します。指定されなかった場合、標準の XMLParser パーザを使用します。 Element インスタンスを返します。

xml.etree.ElementTree.XMLID(text, parser=None)

文字列定数で与えられた XML 断片を解析し、要素 ID と要素を対応付ける辞書を返します。 text には XMLデータを含んだ文字列を指定します。 parser はオプションで、パーザのインスタンスを指定します。指定されなかった場合、標準の XMLParser パーザを使用します。 Element のインスタンスと辞書のタプルを返します。

XInclude サポート

This module provides limited support for XInclude directives, via the xml.etree.ElementInclude helper module. This module can be used to insert subtrees and text strings into element trees, based on information in the tree.

使用例

Here's an example that demonstrates use of the XInclude module. To include an XML document in the current document, use the {http://www.w3.org/2001/XInclude}include element and set the parse attribute to "xml", and use the href attribute to specify the document to include.

<?xml version="1.0"?>
<document xmlns:xi="http://www.w3.org/2001/XInclude">
  <xi:include href="source.xml" parse="xml" />
</document>

By default, the href attribute is treated as a file name. You can use custom loaders to override this behaviour. Also note that the standard helper does not support XPointer syntax.

To process this file, load it as usual, and pass the root element to the xml.etree.ElementTree module:

from xml.etree import ElementTree, ElementInclude

tree = ElementTree.parse("document.xml")
root = tree.getroot()

ElementInclude.include(root)

The ElementInclude module replaces the {http://www.w3.org/2001/XInclude}include element with the root element from the source.xml document. The result might look something like this:

<document xmlns:xi="http://www.w3.org/2001/XInclude">
  <para>This is a paragraph.</para>
</document>

If the parse attribute is omitted, it defaults to "xml". The href attribute is required.

To include a text document, use the {http://www.w3.org/2001/XInclude}include element, and set the parse attribute to "text":

<?xml version="1.0"?>
<document xmlns:xi="http://www.w3.org/2001/XInclude">
  Copyright (c) <xi:include href="year.txt" parse="text" />.
</document>

The result might look something like:

<document xmlns:xi="http://www.w3.org/2001/XInclude">
  Copyright (c) 2003.
</document>

リファレンス

関数

xml.etree.ElementInclude.default_loader(href, parse, encoding=None)

Default loader. This default loader reads an included resource from disk. href is a URL. parse is for parse mode either "xml" or "text". encoding is an optional text encoding. If not given, encoding is utf-8. Returns the expanded resource. If the parse mode is "xml", this is an ElementTree instance. If the parse mode is "text", this is a Unicode string. If the loader fails, it can return None or raise an exception.

xml.etree.ElementInclude.include(elem, loader=None, base_url=None, max_depth=6)

This function expands XInclude directives. elem is the root element. loader is an optional resource loader. If omitted, it defaults to default_loader(). If given, it should be a callable that implements the same interface as default_loader(). base_url is base URL of the original file, to resolve relative include file references. max_depth is the maximum number of recursive inclusions. Limited to reduce the risk of malicious content explosion. Pass a negative value to disable the limitation.

Returns the expanded resource. If the parse mode is "xml", this is an ElementTree instance. If the parse mode is "text", this is a Unicode string. If the loader fails, it can return None or raise an exception.

バージョン 3.9 で変更: Added the base_url and max_depth parameters.

Element オブジェクト

class xml.etree.ElementTree.Element(tag, attrib={}, **extra)

要素クラスです。この関数は Element インターフェースを定義すると同時に、そのリファレンス実装を提供します。

要素名、属性名、および属性値はバイト文字列でも Unicode 文字列でも構いません。 tag には要素名を指定します。attrib はオプションで、要素と属性を含む辞書を指定します。extra は追加の属性で、キーワード引数として与えます。要素インスタンスを返します。

tag

この要素が表すデータの種類を示す文字列です (言い替えると、要素の型です)。

text
tail

これらの属性は要素に結びつけられた付加的なデータを保持するのに使われます。これらの属性値はたいてい文字列ですが、アプリケーション固有のオブジェクトであって構いません。要素が XML ファイルから作られる場合、 text 属性は要素の開始タグとその最初の子要素または終了タグまでのテキストか、あるいは None を保持し、 tail 属性は要素の終了タグと次のタグまでのテキストか、あるいは None を保持します。このような XML データ

<a><b>1<c>2<d/>3</c></b>4</a>

の場合、 a 要素は text, tail 属性ともに None, b 要素は text"1"tail"4", c 要素は text"2"tailNone, d 要素 は textNonetail"3" をそれぞれ保持します。

要素の内側のテキストを収集するためには、itertext() を参照してください。例えば "".join(element.itertext()) のようにします。

アプリケーションはこれらの属性に任意のオブジェクトを格納できます。

attrib

要素の属性を保持する辞書です。 attrib の値は常に書き換え可能な Python 辞書ですが、ElementTree の実装によっては別の内部表現を使用し、要求されたときにだけ辞書を作るようにしているかもしれません。そうした実装の利益を享受するために、可能な限り下記の辞書メソッドを通じて使用してください。

以下の辞書風メソッドが要素の属性に対して動作します。

clear()

要素をリセットします。この関数は全ての子要素を削除し、全属性を消去し、テキストとテール属性を None に設定します。

get(key, default=None)

要素の key という名前の属性を取得します。

属性の値、または属性がない場合は default を返します。

items()

要素の属性を (名前, 値) ペアのシーケンスとして返します。返される属性の順番は決まっていません。

keys()

要素の属性名をリストとして返します。返される名前の順番は決まっていません。

set(key, value)

要素の属性 keyvalue をセットします。

以下のメソッドは要素の子要素 (副要素) に対して動作します。

append(subelement)

要素 subelement を、要素の子要素の内部リストの末尾に追加します。subelement Element でない場合、TypeError を送出します。

extend(subelements)

0 個以上の要素のシーケンスオブジェクトによって subelements を拡張します。subelementsElement でない場合、TypeError を送出します。

バージョン 3.2 で追加.

find(match, namespaces=None)

Finds the first subelement matching match. match may be a tag name or a path. Returns an element instance or None. namespaces is an optional mapping from namespace prefix to full name. Pass '' as prefix to move all unprefixed tag names in the expression into the given namespace.

findall(match, namespaces=None)

Finds all matching subelements, by tag name or path. Returns a list containing all matching elements in document order. namespaces is an optional mapping from namespace prefix to full name. Pass '' as prefix to move all unprefixed tag names in the expression into the given namespace.

findtext(match, default=None, namespaces=None)

Finds text for the first subelement matching match. match may be a tag name or a path. Returns the text content of the first matching element, or default if no element was found. Note that if the matching element has no text content an empty string is returned. namespaces is an optional mapping from namespace prefix to full name. Pass '' as prefix to move all unprefixed tag names in the expression into the given namespace.

insert(index, subelement)

要素内の指定された位置に subelement を挿入します。subelementElement でない場合、TypeError を送出します。

iter(tag=None)

現在の要素を根とする木の イテレータ を作成します。イテレータは現在の要素とそれ以下のすべての要素を、文書内での出現順 (深さ優先順) でイテレートします。 tagNone または '*' でない場合、与えられたタグに等しいものについてのみイテレータから返されます。イテレート中に木構造が変更された場合の結果は未定義です。

バージョン 3.2 で追加.

iterfind(match, namespaces=None)

タグ名または パス にマッチするすべての子要素を検索します。マッチしたすべての要素を文書内での出現順で yield するイテレータを返します。namespaces はオプションで、名前空間接頭辞と完全名を対応付けるマップオブジェクトを指定します。

バージョン 3.2 で追加.

itertext()

テキストのイテレータを作成します。イテレータは、この要素とすべての子要素を文書上の順序で巡回し、すべての内部のテキストを返します。

バージョン 3.2 で追加.

makeelement(tag, attrib)

現在の要素と同じ型の新しい要素オブジェクトを作成します。このメソッドは呼び出さずに、 SubElement() ファクトリ関数を使って下さい。

remove(subelement)

要素から subelement を削除します。find* メソッド群と異なり、このメソッドは要素をインスタンスの同一性で比較します。タグや内容では比較しません。

Element オブジェクトは以下のシーケンス型のメソッドを、サブ要素を操作するためにサポートします: __delitem__(), __getitem__(), __setitem__(), __len__().

Caution: Elements with no subelements will test as False. Testing the truth value of an Element is deprecated and will raise an exception in Python 3.14. Use specific len(elem) or elem is None test instead.:

element = root.find('foo')

if not element:  # careful!
    print("element not found, or element has no subelements")

if element is None:
    print("element not found")

バージョン 3.12 で変更: Testing the truth value of an Element emits DeprecationWarning.

Prior to Python 3.8, the serialisation order of the XML attributes of elements was artificially made predictable by sorting the attributes by their name. Based on the now guaranteed ordering of dicts, this arbitrary reordering was removed in Python 3.8 to preserve the order in which attributes were originally parsed or created by user code.

In general, user code should try not to depend on a specific ordering of attributes, given that the XML Information Set explicitly excludes the attribute order from conveying information. Code should be prepared to deal with any ordering on input. In cases where deterministic XML output is required, e.g. for cryptographic signing or test data sets, canonical serialisation is available with the canonicalize() function.

In cases where canonical output is not applicable but a specific attribute order is still desirable on output, code should aim for creating the attributes directly in the desired order, to avoid perceptual mismatches for readers of the code. In cases where this is difficult to achieve, a recipe like the following can be applied prior to serialisation to enforce an order independently from the Element creation:

def reorder_attributes(root):
    for el in root.iter():
        attrib = el.attrib
        if len(attrib) > 1:
            # adjust attribute order, e.g. by sorting
            attribs = sorted(attrib.items())
            attrib.clear()
            attrib.update(attribs)

ElementTree オブジェクト

class xml.etree.ElementTree.ElementTree(element=None, file=None)

ElementTree ラッパークラスです。このクラスは要素の全階層を表現し、さらに標準 XML との相互変換を追加しています。

element は根要素です。file が指定されている場合、その XML ファイルの内容により木は初期化されます。

_setroot(element)

この木の根要素を置き換えます。従って現在の木の内容は破棄され、与えられた要素が代わりに使われます。注意して使ってください。 element は要素インスタンスです。

find(match, namespaces=None)

Element.find() と同じで、木の根要素を起点とします。

findall(match, namespaces=None)

Element.findall() と同じで、木の根要素を起点とします。

findtext(match, default=None, namespaces=None)

Element.findtext() と同じで、木の根要素を起点とします。

getroot()

この木のルート要素を返します。

iter(tag=None)

根要素に対する、木を巡回するイテレータを返します。イテレータは木のすべての要素に渡ってセクション順にループします。tag は探したいタグです (デフォルトではすべての要素を返します)。

iterfind(match, namespaces=None)

Element.iterfind() と同じで、木の根要素を起点とします。

バージョン 3.2 で追加.

parse(source, parser=None)

外部の XML 断片をこの要素木に入れます。source にはファイル名か ファイルオブジェクト を指定します。parser はオプションで、パーザインスタンスを指定します。パーザが指定されない場合、標準の XMLParser パーザが使用されます。断片の根要素を返します。

write(file, encoding='us-ascii', xml_declaration=None, default_namespace=None, method='xml', *, short_empty_elements=True)

要素の木をファイルに XML として書き込みます。 file は、書き込み用に開かれたファイル名または ファイルオブジェクト です。 encoding [1] は出力エンコーディング(デフォルトは US-ASCII)です。 xml_declaration は、 XML 宣言がファイルに書かれるかどうかを制御します。 False の場合は常に書かれず、 True の場合は常に書かれ、 None の場合は US-ASCII 、 UTF-8 、 Unicode 以外の場合に書かれます (デフォルトは None です)。 default_namespace でデフォルトの XML 名前空間 ("xmlns" 用) を指定します。 method"xml", "html", "text" のいずれかです (デフォルトは "xml" です)。 キーワード専用の short_empty_elements 引数は、内容がない属性のフォーマットを制御します。 True (既定) の場合、単一の空要素タグとして書かれ、False の場合、開始タグと終了タグのペアとしてかかれます。

出力は引数 encoding によって、文字列 (str) かバイト列 (bytes) になります。encoding"unicode" の場合、出力は文字列になり、それ以外ではバイト列になります。fileファイルオブジェクト の場合、型が衝突する場合があります。文字列をバイト列ファイルへ書き込んだり、その逆を行わないよう注意してください。

バージョン 3.4 で変更: Added the short_empty_elements parameter.

バージョン 3.8 で変更: write() メソッドはユーザーが指定した属性の順序を保持するようになりました。

以下はこれから操作する XML ファイルです:

<html>
    <head>
        <title>Example page</title>
    </head>
    <body>
        <p>Moved to <a href="http://example.org/">example.org</a>
        or <a href="http://example.com/">example.com</a>.</p>
    </body>
</html>

第 1 段落のすべてのリンクの "target" 属性を変更する例:

>>> from xml.etree.ElementTree import ElementTree
>>> tree = ElementTree()
>>> tree.parse("index.xhtml")
<Element 'html' at 0xb77e6fac>
>>> p = tree.find("body/p")     # Finds first occurrence of tag p in body
>>> p
<Element 'p' at 0xb77ec26c>
>>> links = list(p.iter("a"))   # Returns list of all links
>>> links
[<Element 'a' at 0xb77ec2ac>, <Element 'a' at 0xb77ec1cc>]
>>> for i in links:             # Iterates through all found links
...     i.attrib["target"] = "blank"
...
>>> tree.write("output.xhtml")

QName オブジェクト

class xml.etree.ElementTree.QName(text_or_uri, tag=None)

QName ラッパーです。 このクラスは QName 属性値をラップし、出力時に適切な名前空間の扱いを得るために使われます。 text_or_uri は {uri}local という形式の QName 値を含む文字列、または tag 引数が与えられた場合には QName の URI 部分の文字列です。 tag が与えられた場合、一つめの引数は URI と解釈され、この引数はローカル名と解釈されます。 QName インスタンスは不透明です。

TreeBuilder オブジェクト

class xml.etree.ElementTree.TreeBuilder(element_factory=None, *, comment_factory=None, pi_factory=None, insert_comments=False, insert_pis=False)

汎用の要素構造ビルダー。これは start, data, end, comment, pi のメソッド呼び出しの列を整形式の要素構造に変換します。このクラスを使うと、好みの XML 構文解析器、または他の XML に似た形式の構文解析器を使って、要素構造を作り出すことができます。

element_factory, when given, must be a callable accepting two positional arguments: a tag and a dict of attributes. It is expected to return a new element instance.

The comment_factory and pi_factory functions, when given, should behave like the Comment() and ProcessingInstruction() functions to create comments and processing instructions. When not given, the default factories will be used. When insert_comments and/or insert_pis is true, comments/pis will be inserted into the tree if they appear within the root element (but not outside of it).

close()

ビルダのバッファをフラッシュし、最上位の文書要素を返します。戻り値は Element インスタンスになります。

data(data)

現在の要素にテキストを追加します。 data は文字列です。バイト文字列もしくは Unicode 文字列でなければなりません。

end(tag)

現在の要素を閉じます。 tag は要素の名前です。閉じられた要素を返します。

start(tag, attrs)

新しい要素を開きます。 tag は要素の名前です。 attrs は要素の属性を保持した辞書です。開かれた要素を返します。

comment(text)

Creates a comment with the given text. If insert_comments is true, this will also add it to the tree.

バージョン 3.8 で追加.

pi(target, text)

Creates a process instruction with the given target name and text. If insert_pis is true, this will also add it to the tree.

バージョン 3.8 で追加.

加えて、カスタムの TreeBuilder オブジェクトは以下のメソッドを提供できます:

doctype(name, pubid, system)

doctype 宣言を処理します。 name は doctype 名です。 pubid は公式の識別子です。 system はシステム識別子です。このメソッドはデフォルトの TreeBuilder クラスには存在しません。

バージョン 3.2 で追加.

start_ns(prefix, uri)

Is called whenever the parser encounters a new namespace declaration, before the start() callback for the opening element that defines it. prefix is '' for the default namespace and the declared namespace prefix name otherwise. uri is the namespace URI.

バージョン 3.8 で追加.

end_ns(prefix)

Is called after the end() callback of an element that declared a namespace prefix mapping, with the name of the prefix that went out of scope.

バージョン 3.8 で追加.

class xml.etree.ElementTree.C14NWriterTarget(write, *, with_comments=False, strip_text=False, rewrite_prefixes=False, qname_aware_tags=None, qname_aware_attrs=None, exclude_attrs=None, exclude_tags=None)

A C14N 2.0 writer. Arguments are the same as for the canonicalize() function. This class does not build a tree but translates the callback events directly into a serialised form using the write function.

バージョン 3.8 で追加.

XMLParser オブジェクト

class xml.etree.ElementTree.XMLParser(*, target=None, encoding=None)

このクラスは、このモジュールの構成要素のうち、低水準のものです。効率的でイベントベースのXMLパースのため、xml.parsers.expat を使用します。feed() メソッドで XML データをインクリメンタルに受け取り、target オブジェクトのコールバックを呼び出すことで、パースイベントをプッシュ API に変換します。target が省略された場合、標準の TreeBuilder が使用されます。 encoding [1] が指定された場合、このあたいは XML ファイル内で指定されたエンコーディングを上書きします。

バージョン 3.8 で変更: Parameters are now keyword-only. The html argument no longer supported.

close()

パーザへのデータの提供を完了します。構築中に渡される targetclose() メソッドを呼び出す結果を返します。既定では、これがトップレベルのドキュメント要素になります。

feed(data)

パーザへデータを入力します。 data はエンコードされたデータです。

flush()

Triggers parsing of any previously fed unparsed data, which can be used to ensure more immediate feedback, in particular with Expat >=2.6.0. The implementation of flush() temporarily disables reparse deferral with Expat (if currently enabled) and triggers a reparse. Disabling reparse deferral has security consequences; please see xml.parsers.expat.xmlparser.SetReparseDeferralEnabled() for details.

Note that flush() has been backported to some prior releases of CPython as a security fix. Check for availability of flush() using hasattr() if used in code running across a variety of Python versions.

バージョン 3.13 で追加.

XMLParser.feed()targetstart(tag, attrs_dict) メソッドをそれぞれの開始タグに対して呼び、また end(tag) メソッドを終了タグに対して呼び、そしてデータを data(data) メソッドで処理します。サポートされているその他のコールバックメソッドについては、 TreeBuilder クラスを参照してください。XMLParser.close()targetclose() メソッドを呼びます。 XMLParser は木構造を構築する以外にも使えます。以下の例では、XML ファイルの最高の深さを数えます。

>>> from xml.etree.ElementTree import XMLParser
>>> class MaxDepth:                     # The target object of the parser
...     maxDepth = 0
...     depth = 0
...     def start(self, tag, attrib):   # Called for each opening tag.
...         self.depth += 1
...         if self.depth > self.maxDepth:
...             self.maxDepth = self.depth
...     def end(self, tag):             # Called for each closing tag.
...         self.depth -= 1
...     def data(self, data):
...         pass            # We do not need to do anything with data.
...     def close(self):    # Called when all data has been parsed.
...         return self.maxDepth
...
>>> target = MaxDepth()
>>> parser = XMLParser(target=target)
>>> exampleXml = """
... <a>
...   <b>
...   </b>
...   <b>
...     <c>
...       <d>
...       </d>
...     </c>
...   </b>
... </a>"""
>>> parser.feed(exampleXml)
>>> parser.close()
4

XMLPullParser オブジェクト

class xml.etree.ElementTree.XMLPullParser(events=None)

非ブロックアプリケーションに適したプルパーザです。入力側の API は XMLParser のものと似ていますが、コールバックターゲットに呼び出しをプッシュするのではなく、 XMLPullParser はパースイベントの内部リストを収集し、ユーザーがそこから読み出すことができます。events は、呼び出し元に報告するイベントのシーケンスです。サポートされているイベントは、文字列の "start", "end", "comment", "pi", "start-ns", "end-ns" ("ns" イベントは、名前空間の詳細情報の取得に使用) です。events が省略された場合、 "end" イベントのみが報告されます。

feed(data)

指定したバイトデータをパーザに与えます。

flush()

Triggers parsing of any previously fed unparsed data, which can be used to ensure more immediate feedback, in particular with Expat >=2.6.0. The implementation of flush() temporarily disables reparse deferral with Expat (if currently enabled) and triggers a reparse. Disabling reparse deferral has security consequences; please see xml.parsers.expat.xmlparser.SetReparseDeferralEnabled() for details.

Note that flush() has been backported to some prior releases of CPython as a security fix. Check for availability of flush() using hasattr() if used in code running across a variety of Python versions.

バージョン 3.13 で追加.

close()

パーザに、データストリームが終了したことを伝えます。XMLParser.close() とは異なり、このメソッドは常に None を返します。パーザがクローズした時にまだ帰って来ていないイベントは、まだ read_events() で読むことができます。

read_events()

Return an iterator over the events which have been encountered in the data fed to the parser. The iterator yields (event, elem) pairs, where event is a string representing the type of event (e.g. "end") and elem is the encountered Element object, or other context value as follows.

  • start, end: the current Element.

  • comment, pi: the current comment / processing instruction

  • start-ns: a tuple (prefix, uri) naming the declared namespace mapping.

  • end-ns: None (this may change in a future version)

read_events() の前の呼び出しで提供されたイベントは、再度 yield されることはありません。イベントは、イテレータから取得された場合にのみ内部キューから消費されるため、read_events() から取得されたイテレータに対して複数の読み出しを並行して反復的に行うと、予期せぬ結果が引き起こされます。

注釈

XMLPullParser は "start" イベントを発行した時に開始タグの文字 ">" が現れたことだけを保証します。そのため、属性は定義されますが、その時点ではテキストの内容も tail 属性も定義されていません。子要素にもそれが存在する、しないにかかわらず同じ物が適用されます。

全部揃った要素が必要ならば、"end" イベントを探してください。

バージョン 3.4 で追加.

バージョン 3.8 で変更: イベント comment, pi が追加されました。

例外

class xml.etree.ElementTree.ParseError

解析に失敗した時、このモジュールの様々なメソッドから送出される XML 解析エラーです。この例外のインスタンスが表す文字列は、ユーザフレンドリなメッセージを含んでいます。その他に、以下の属性も利用できます:

code

expat パーザからの数値エラーコードです。エラーコードの一覧とそれらの意味については、xml.parsers.expat のドキュメントを参照してください。

position

エラーが発生した場所を示す linecolumn 番号のタプルです。

脚注