xml.parsers.expat --- Expat を使用した高速な XML 解析¶
注釈
If you need to parse untrusted or unauthenticated data, see XML security.
xml.parsers.expat モジュールは、検証 (validation) を行わない XML パーザ (parser, 解析器)、Expat への Python インターフェースです。モジュールは一つの拡張型 xmlparser を提供します。これは XMLパーザの現在の状況を表します。一旦 xmlparser オブジェクトを生成すると、オブジェクトの様々な属性をハンドラ関数 (handler function) に設定できます。その後、XML 文書をパーザに入力すると、 XML文書の文字列とマークアップに応じてハンドラ関数が呼び出されます。
このモジュールでは、Expatパーザへのアクセスを提供するために pyexpat モジュールを使用します。
pyexpat モジュールの直接使用は非推奨です。
This module provides the following exception, type object and data items:
- exception xml.parsers.expat.ExpatError¶
Expat がエラーを報告したときに例外を送出します。 Expatのエラーを解釈する上での詳細な情報は、 ExpatError 例外 を参照してください。
- exception xml.parsers.expat.error¶
ExpatErrorの別名です。
- xml.parsers.expat.XMLParserType¶
ParserCreate()関数から返された戻り値の型を示します。
- xml.parsers.expat.EXPAT_VERSION¶
The version string of the Expat library loaded by the interpreter, like
'expat_2.8.4'.
- xml.parsers.expat.version_info¶
The version of the Expat library loaded by the interpreter, as a tuple of three integers: major, minor and micro version.
- xml.parsers.expat.features¶
The list of the features with which the loaded Expat library was compiled, as
(name, value)pairs. The value is only meaningful for features which have one, like'XML_CONTEXT_BYTES'or the default protection limits'XML_BLAP_ACT_THRES'and'XML_AT_MAX_AMP'; for other features, like'XML_DTD'and'XML_NS', the value is0and only the presence of the name is significant.
xml.parsers.expat モジュールには以下の 2 つの関数が収められています:
- xml.parsers.expat.ErrorString(errno)¶
与えられたエラー番号 errno を解説する文字列を返します。
- xml.parsers.expat.ParserCreate(encoding=None, namespace_separator=None, intern=None)¶
新しい
xmlparserオブジェクトを作成し、返します。 encoding が指定されていた場合、XMLデータで使われている文字列のエンコード名でなければなりません。 Expatは、Pythonのように多くのエンコードをサポートしておらず、またエンコーディングのレパートリを拡張することはできません; サポートするエンコードは、UTF-8, UTF-16, ISO-8859-1 (Latin1), ASCII です。 encoding [1] が指定されると、文書に対する明示的、非明示的なエンコード指定を上書き (override) します。Parsers created through
ParserCreate()are called "root" parsers, in the sense that they do not have any parent parser attached. Non-root parsers are created byparser.ExternalEntityParserCreate.Expat はオプションで XML 名前空間の処理を行うことができます。これは引数 namespace_separator に値を指定することで有効になります。この値は、1文字の文字列でなければなりません; 文字列が誤った長さを持つ場合には
ValueErrorが送出されます (Noneは値の省略と見なされます)。名前空間の処理が可能なとき、名前空間に属する要素と属性が展開されます。要素のハンドラであるStartElementHandlerとEndElementHandlerに渡された要素名は、名前空間の URI、名前空間の区切り文字、要素名のローカル部を連結したものになります。名前空間の区切り文字が 0 バイト (chr(0)) の場合、名前空間の URI とローカル部は区切り文字なしで連結されます。たとえば、namespace_separator に空白文字(
' ')がセットされ、次のような文書が解析されるとします:<?xml version="1.0"?> <root xmlns = "http://default-namespace.org/" xmlns:py = "http://www.python.org/ns/"> <py:elem1 /> <elem2 xmlns="" /> </root>
StartElementHandlerは各要素ごとに次のような文字列を受け取ります:http://default-namespace.org/ root http://www.python.org/ns/ elem1 elem2
intern, if given, must be a dictionary. It is used to intern the names of elements and attributes, and is available as the
internattribute. By default a new empty dictionary is created for every parser.pyexpatが使っているExpatライブラリの制限により、返されるxmlparserインスタンスは単独の XML ドキュメントの解析にしか使えません。それぞれのドキュメントごとに別々のパーサのインスタンスを作るためにParserCreateを呼び出してください。
参考
- The Expat XML Parser
Expatプロジェクトのホームページ。
XMLParser オブジェクト¶
xmlparser オブジェクトは以下のようなメソッドを持ちます:
- xmlparser.Parse(data[, isfinal])¶
Parses the contents of data, calling the appropriate handler functions to process the parsed data. data can be a bytes-like object or a string. If it is a string, the encoding declaration in the XML data is ignored, and the data is parsed as already decoded text. isfinal must be true on the final call to this method; it allows the parsing of a single file in fragments, not the submission of multiple files. data can be empty at any time.
- xmlparser.ParseFile(file)¶
Parse XML data reading from the object file. file only needs to provide the
read(nbytes)method, which returns bytes, and an empty bytes object when there's no more data. Text files are not supported; useParse()for data which is already decoded.
- xmlparser.SetBase(base)¶
(XML) 宣言中のシステム識別子中の相対 URI を解決するための、基底 URI を設定します。相対識別子の解決はアプリケーションに任されます: この値は関数
ExternalEntityRefHandler()やNotationDeclHandler(),UnparsedEntityDeclHandler()に引数 base としてそのまま渡されます。
- xmlparser.GetInputContext()¶
Returns the input data which generated the current event as a
bytesobject. The data is in the encoding of the entity which contains the text. It extends to the end of the currently buffered input, therefore it can contain also the data of the following events, and if the event was generated by a large amount of text, not all of it may be available. When called while an event handler is not active, the return value isNone.
- xmlparser.ExternalEntityParserCreate(context[, encoding])¶
親パーサーが解析する内容から参照される、解析対象の外部エンティティを解析するための「子」パーサーを作成します。 context 引数には、後述の
ExternalEntityRefHandler()ハンドラー関数に渡された文字列を指定します。 子パーサーのordered_attributesとspecified_attributesには、このパーサーの値が設定されます。
- xmlparser.SetParamEntityParsing(flag)¶
パラメータエンティティ (外部DTDサブセットを含む) の解析を制御します。 flag の有効な値は、
XML_PARAM_ENTITY_PARSING_NEVER,XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE,XML_PARAM_ENTITY_PARSING_ALWAYSです。 フラグの設定に成功した場合は真を返します。
- xmlparser.UseForeignDTD([flag])¶
flag の値をデフォルトのtrueにすると、Expatは代わりのDTDをロードするため、すべての引数に
Noneを設定してExternalEntityRefHandlerを呼び出します。XML文書が文書型定義を持っていなければ、ExternalEntityRefHandlerが呼び出しますが、StartDoctypeDeclHandlerとEndDoctypeDeclHandlerは呼び出されません。flag にfalseを与えると、メソッドが前回呼ばれた時のtrueの設定が解除されますが、他には何も起こりません。
このメソッドは
Parse()またはParseFile()メソッドが呼び出される前にだけ呼び出されます;これら2つのメソッドのどちらかが呼び出されたあとにメソッドが呼ばれると、codeに定数errors.codes[errors.XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING]が設定されて例外ExpatErrorが送出されます。
- xmlparser.SetReparseDeferralEnabled(enabled)¶
警告
SetReparseDeferralEnabled(False)の呼び出しには、以下で説明するセキュリティ上の影響があります。SetReparseDeferralEnabledメソッドを使う前に、これらの影響を理解してください。Expat 2.6.0 では「再解析の遅延」というセキュリティ機構が導入されました。 大きなトークンの再解析によって実行時間が二次的に増大し、サービス拒否が起こるのを防ぐため、未完了のトークンの再解析はデフォルトで十分な量の入力が集まるまで遅延されます。 この遅延により、Expat に渡す入力チャンクの大きさによっては、新しい入力をパーサーに渡した直後には登録済みのハンドラーが呼び出されなくなります。 即時の応答が必要で、大きなトークンによるサービス拒否への対策を自身で担う場合、
SetReparseDeferralEnabled(False)を呼び出すと、現在の Expat パーサーインスタンスの再解析の遅延を一時的または継続的に無効化できます。SetReparseDeferralEnabled(True)を呼び出すと、再解析の遅延を再び有効にできます。Note that
SetReparseDeferralEnabled()has been backported to some prior releases of CPython as a security fix. Check for availability ofSetReparseDeferralEnabled()usinghasattr()if used in code running across a variety of Python versions.Added in version 3.13.
- xmlparser.GetReparseDeferralEnabled()¶
この Expat パーサーインスタンスで再解析の遅延が現在有効かどうかを返します。
Added in version 3.13.
xmlparser objects have the following methods to tune protections
against some common XML vulnerabilities.
- xmlparser.SetBillionLaughsAttackProtectionActivationThreshold(threshold, /)¶
Sets the number of output bytes needed to activate protection against billion laughs attacks.
The number of output bytes includes amplification from entity expansion and reading DTD files.
Parser objects usually have a protection activation threshold of 8 MiB, but the actual default value depends on the underlying Expat library.
An
ExpatErroris raised if this method is called on a non-root parser. The correspondinglinenoandoffsetshould not be used as they may have no special meaning.注釈
Activation thresholds below 4 MiB are known to break support for DITA 1.3 payload and are hence not recommended.
Added in version 3.13.14.
- xmlparser.SetBillionLaughsAttackProtectionMaximumAmplification(max_factor, /)¶
Sets the maximum tolerated amplification factor for protection against billion laughs attacks.
The amplification factor is calculated as
(direct + indirect) / directwhile parsing, wheredirectis the number of bytes read from the primary document in parsing andindirectis the number of bytes added by expanding entities and reading of external DTD files.The max_factor value must be a non-NaN
floatvalue greater than or equal to 1.0. Peak amplifications of factor 15,000 for the entire payload and of factor 30,000 in the middle of parsing have been observed with small benign files in practice. In particular, the activation threshold should be carefully chosen to avoid false positives.Parser objects usually have a maximum amplification factor of 100, but the actual default value depends on the underlying Expat library.
An
ExpatErroris raised if this method is called on a non-root parser or if max_factor is outside the valid range. The correspondinglinenoandoffsetshould not be used as they may have no special meaning.注釈
The maximum amplification factor is only considered if the threshold that can be adjusted by
SetBillionLaughsAttackProtectionActivationThreshold()is exceeded.Added in version 3.13.14.
- xmlparser.SetAllocTrackerActivationThreshold(threshold, /)¶
Sets the number of allocated bytes of dynamic memory needed to activate protection against disproportionate use of RAM.
Parser objects usually have an allocation activation threshold of 64 MiB, but the actual default value depends on the underlying Expat library.
An
ExpatErroris raised if this method is called on a non-root parser. The correspondinglinenoandoffsetshould not be used as they may have no special meaning.Added in version 3.13.10.
- xmlparser.SetAllocTrackerMaximumAmplification(max_factor, /)¶
Sets the maximum amplification factor between direct input and bytes of dynamic memory allocated.
The amplification factor is calculated as
allocated / directwhile parsing, wheredirectis the number of bytes read from the primary document in parsing andallocatedis the number of bytes of dynamic memory allocated in the parser hierarchy.The max_factor value must be a non-NaN
floatvalue greater than or equal to 1.0. Amplification factors greater than 100.0 can be observed near the start of parsing even with benign files in practice. In particular, the activation threshold should be carefully chosen to avoid false positives.Parser objects usually have a maximum amplification factor of 100, but the actual default value depends on the underlying Expat library.
An
ExpatErroris raised if this method is called on a non-root parser or if max_factor is outside the valid range. The correspondinglinenoandoffsetshould not be used as they may have no special meaning.注釈
The maximum amplification factor is only considered if the threshold that can be adjusted by
SetAllocTrackerActivationThreshold()is exceeded.Added in version 3.13.10.
xmlparser オブジェクトは次のような属性を持ちます:
- xmlparser.buffer_size¶
buffer_textが真の時に使われるバッファのサイズです。この属性に新しい整数値を代入することで違うバッファサイズにできます。サイズが変えられるときにバッファはフラッシュされます。
- xmlparser.buffer_text¶
この属性を真にすると、
xmlparserオブジェクトは Expat が返すテキスト内容をバッファに保持し、CharacterDataHandler()コールバックが複数回呼ばれることをできるだけ避けます。 Expat は通常、改行のたびに文字データを分割するため、この設定で性能が大幅に向上することがあります。 デフォルトは偽で、いつでも変更できます。 偽の場合、改行を含まないデータも分割されることに注意してください。
- xmlparser.buffer_used¶
buffer_textが有効な場合、バッファに保持されているバイト数です。 これらのバイトは UTF-8 でエンコードされたテキストを表します。buffer_textが偽の場合、この属性は意味を持ちません。
- xmlparser.ordered_attributes¶
この属性をゼロ以外の整数にすると、報告される(XMLノードの) 属性を辞書型ではなくリスト型にします。属性は文書のテキスト中の出現順で示されます。それぞれの属性は、2つのリストのエントリ: 属性名とその値、が与えられます。 (このモジュールの古いバージョンでも、同じフォーマットが使われています。) デフォルトでは、この属性はデフォルトでは偽となりますが、いつでも変更可能です。
- xmlparser.specified_attributes¶
ゼロ以外の整数にすると、パーザは文書のインスタンスで特定される属性だけを報告し、属性宣言から導出された属性は報告しないようになります。この属性が指定されたアプリケーションでは、XMLプロセッサの振る舞いに関する標準に従うために必要とされる (文書型) 宣言によって、どのような付加情報が利用できるのかということについて特に注意を払わなければなりません。デフォルトで、この属性は偽となりますが、いつでも変更可能です。
- xmlparser.intern¶
The dictionary used to intern the names of elements and attributes. It is either the dictionary passed as the intern argument of
ParserCreate(), or a new dictionary created for this parser.
- xmlparser.namespace_prefixes¶
If set to a true value, and namespace processing is enabled, the namespace prefix is reported as the third part of the expanded name, separated by the namespace separator. Names which have no prefix are not affected. By default, this attribute is false; it may be changed at any time.
以下の属性には、 xmlparser オブジェクトで最も最近に起きたエラーに関する値が入っており、また Parse() または ParseFile() メソッドが xml.parsers.expat.ExpatError 例外を送出した際にのみ正しい値となります。
- xmlparser.ErrorByteIndex¶
エラーが発生したバイトのインデクスです。
- xmlparser.ErrorCode¶
エラーを特定する数値によるコードです。この値は
ErrorString()に渡したり、errorsオブジェクトで定義された内容と比較できます。
- xmlparser.ErrorColumnNumber¶
エラーの発生したカラム番号です。
- xmlparser.ErrorLineNumber¶
エラーの発生した行番号です。
以下の属性は xmlparser オブジェクトがその時パースしている位置に関する値を保持しています。
コールバックがパースイベントを報告している間、これらの値はイベントを発生させた文字列の先頭の位置を指し示します。
コールバックの外から参照された時には、対応するコールバックの有無にかかわらず、最後のパースイベントの直後の位置を示します。
- xmlparser.CurrentByteIndex¶
パーサへの入力の、現在のバイトインデックス。
- xmlparser.CurrentColumnNumber¶
パーサへの入力の、現在のカラム番号。
- xmlparser.CurrentLineNumber¶
パーサへの入力の、現在の行番号。
以下に指定可能なハンドラのリストを示します。 xmlparser オブジェクト o にハンドラを指定するには、 o.handlername = func を使用します。 handlername は、以下のリストに挙げた値をとらなければならず、また func は正しい数の引数を受理する呼び出し可能なオブジェクトでなければなりません。引数は特に明記しない限り、すべて文字列となります。
- xmlparser.XmlDeclHandler(version, encoding, standalone)¶
Called when the XML declaration is parsed. The XML declaration is the (optional) declaration of the applicable version of the XML recommendation, the encoding of the document text, and an optional "standalone" declaration. version and encoding will be strings, and standalone will be
1if the document is declared standalone,0if it is declared not to be standalone, or-1if the standalone clause was omitted.
- xmlparser.StartDoctypeDeclHandler(doctypeName, systemId, publicId, has_internal_subset)¶
Called when Expat begins parsing the document type declaration (
<!DOCTYPE ...). The doctypeName is provided exactly as presented. The systemId and publicId parameters give the system and public identifiers if specified, orNoneif omitted. has_internal_subset will be true if the document contains an internal document declaration subset.
- xmlparser.EndDoctypeDeclHandler()¶
Called when Expat is done parsing the document type declaration.
- xmlparser.ElementDeclHandler(name, model)¶
それぞれの要素型宣言ごとに呼び出されます。 name は要素型の名前であり、 model は内容モデル (content model) の表現です。
- xmlparser.AttlistDeclHandler(elname, attname, type, default, required)¶
Called for each declared attribute for an element type. If an attribute list declaration declares three attributes, this handler is called three times, once for each attribute. elname is the name of the element to which the declaration applies and attname is the name of the attribute declared. The The attribute type is a string passed as type:
'CDATA','ID','IDREF','IDREFS','ENTITY','ENTITIES','NMTOKEN'or'NMTOKENS', an enumeration like'(x|y)', or a notation list like'NOTATION(n1|n2)'. default gives the default value for the attribute used when the attribute is not specified by the document instance, orNoneif there is no default value (#IMPLIEDvalues). If the attribute is required to be given in the document instance, required will be true.
- xmlparser.StartElementHandler(name, attributes)¶
要素の開始ごとに呼び出されます。 name は要素名を持つ文字列で、 attributes は要素の属性です。
ordered_attributesが真の場合これはリストです (詳細はordered_attributesを参照してください)。 そうでなければ名前を値に対応させる辞書です。
- xmlparser.EndElementHandler(name)¶
要素の終端を処理するごとに呼び出されます。
- xmlparser.ProcessingInstructionHandler(target, data)¶
処理命令を処理するごとに呼び出されます。
- xmlparser.CharacterDataHandler(data)¶
文字データに対して呼び出されます。 通常の文字データ、CDATA としてマークされた内容、無視可能な空白に対して呼び出されます。 これらを区別する必要があるアプリケーションは、
StartCdataSectionHandler、EndCdataSectionHandler、ElementDeclHandlerのコールバックで必要な情報を収集できます。 短い文字データでも分割されることがあり、CharacterDataHandler()が複数回呼び出される場合があります。 これを避けるには、インスタンス属性buffer_textをTrueに設定してください。
- xmlparser.UnparsedEntityDeclHandler(entityName, base, systemId, publicId, notationName)¶
Called for unparsed (NDATA) entity declarations. If this handler is not set, such declarations are reported by
EntityDeclHandler, which is preferred for new code. (The underlying function in the Expat library has been declared obsolete.)
- xmlparser.EntityDeclHandler(entityName, is_parameter_entity, value, base, systemId, publicId, notationName)¶
Called for all entity declarations. For parameter and internal entities, value will be a string giving the declared contents of the entity; this will be
Nonefor external entities. The notationName parameter will beNonefor parsed entities, and the name of the notation for unparsed entities. is_parameter_entity will be true if the entity is a parameter entity or false for general entities (most applications only need to be concerned with general entities).
- xmlparser.NotationDeclHandler(notationName, base, systemId, publicId)¶
記法の宣言 (notation declaration) で呼び出されます。 notationName, base, systemId, および publicId を与える場合、文字列にします。public な識別子が省略された場合、 publicId は
Noneになります。
- xmlparser.StartNamespaceDeclHandler(prefix, uri)¶
要素が名前空間宣言を含んでいる場合に呼び出されます。名前空間宣言は、宣言が配置されている要素に対して
StartElementHandlerが呼び出される前に処理されます。
- xmlparser.EndNamespaceDeclHandler(prefix)¶
名前空間宣言を含む要素の終了タグに達すると呼び出されます。 その要素の名前空間宣言ごとに 1 回ずつ、各宣言のスコープ開始を知らせた
StartNamespaceDeclHandlerとは逆順に呼び出されます。 このハンドラーは、その要素の終了を知らせるEndElementHandlerの後に呼び出されます。
- xmlparser.CommentHandler(data)¶
コメントで呼び出されます。 data はコメントのテキストで、先頭の '
<!--' と末尾の '-->' を除きます。
- xmlparser.StartCdataSectionHandler()¶
CDATA セクションの開始時に呼び出されます。CDATA セクションの構文的な開始と終了位置を識別できるようにするには、このハンドラと
EndCdataSectionHandlerが必要です。
- xmlparser.EndCdataSectionHandler()¶
CDATA セクションの終了時に呼び出されます。
- xmlparser.DefaultHandler(data)¶
XML 文書中で、適用可能なハンドラが指定されていない文字すべてに対して呼び出されます。この文字とは、検出されたことが報告されるが、ハンドラは指定されていないようなコンストラクト (construct) の一部である文字を意味します。
- xmlparser.DefaultHandlerExpand(data)¶
This is the same as the
DefaultHandler, but doesn't inhibit expansion of internal entities. The entity reference will not be passed to the default handler.
- xmlparser.NotStandaloneHandler()¶
XML 文書がスタンドアロンの文書として宣言されていない場合に呼び出されます。外部サブセットやパラメタエンティティへの参照が存在するが、XML 宣言が XML 宣言中で standalone 変数を
yesに設定していない場合に起きます。このハンドラが0を返すと、パーザはXML_ERROR_NOT_STANDALONEを発生させます。このハンドラが設定されていなければ、パーザは前述の事態で例外を送出しません。
- xmlparser.ExternalEntityRefHandler(context, base, systemId, publicId)¶
警告
Implementing a handler that accesses local files and/or the network may create a vulnerability to external entity attacks if
xmlparseris used with user-provided XML content. Please reflect on your threat model before implementing this handler.外部エンティティの参照時に呼び出されます。 base は現在の基底 (base) で、以前の
SetBase()で設定された値になっています。 public、および system の識別子である、 systemId と publicId が指定されている場合、値は文字列です; public 識別子が指定されていない場合、 publicId はNoneになります。 context の値は不明瞭なものであり、以下に記述するようにしか使ってはなりません。外部エンティティが解析されるようにするには、このハンドラを実装しなければなりません。 このハンドラは、
ExternalEntityParserCreate(context)で子パーサーを作り、適切なコールバックを設定してからエンティティを解析する役割を担います。 このハンドラは整数を返さなければなりません;0を返した場合、パーザはXML_ERROR_EXTERNAL_ENTITY_HANDLINGエラーを送出します。 そうでない場合、解析を継続します。このハンドラが与えられておらず、
DefaultHandlerコールバックが指定されていれば、外部エンティティはDefaultHandlerで報告されます。
- xmlparser.SkippedEntityHandler(entityName, is_parameter_entity)¶
Called for entity references which are not expanded, because the parser did not read the declaration of the entity. This happens when the external DTD subset or an external parameter entity is not parsed. is_parameter_entity is true for a parameter entity and false for a general entity.
ExpatError 例外¶
ExpatError 例外はいくつかの興味深い属性を備えています:
- ExpatError.code¶
特定のエラーに対する Expat の内部エラー番号です。
errors.messages辞書はこれらのエラー番号を Expat のエラーメッセージに対応させます。 例えば:from xml.parsers.expat import ParserCreate, ExpatError, errors p = ParserCreate() try: p.Parse(some_xml_document) except ExpatError as err: print("Error:", errors.messages[err.code])
errorsモジュールはエラーメッセージ定数と、それらのメッセージをエラーコードに対応させる辞書codesも提供しています。以下を参照してください。
- ExpatError.lineno¶
エラーが検出された場所の行番号です。最初の行の番号は
1です。
- ExpatError.offset¶
エラーが発生した場所の行内でのオフセットです。最初のカラムの番号は
0です。
使用例¶
以下のプログラムでは、与えられた引数を出力するだけの三つのハンドラを定義しています。
import xml.parsers.expat
# 3 つのハンドラー関数
def start_element(name, attrs):
print('Start element:', name, attrs)
def end_element(name):
print('End element:', name)
def char_data(data):
print('Character data:', repr(data))
p = xml.parsers.expat.ParserCreate()
p.StartElementHandler = start_element
p.EndElementHandler = end_element
p.CharacterDataHandler = char_data
p.Parse("""<?xml version="1.0"?>
<parent id="top"><child1 name="paul">Text goes here</child1>
<child2 name="fred">More text</child2>
</parent>""", 1)
このプログラムの出力は以下のようになります:
Start element: parent {'id': 'top'}
Start element: child1 {'name': 'paul'}
Character data: 'Text goes here'
End element: child1
Character data: '\n'
Start element: child2 {'name': 'fred'}
Character data: 'More text'
End element: child2
Character data: '\n'
End element: parent
内容モデルの記述¶
内容モデルは入れ子になったタプルを使って記述されています。各タプルには以下の 4 つの値が収められています: 型、限定詞 (quantifier)、名前、そして子のタプル。子のタプルは単に内容モデルを記述したものです。
最初の二つのフィールドの値は xml.parsers.expat.model モジュールで定義されている定数です。これらの定数は二つのグループ: モデル型 (model type) グループと限定子 (quantifier) グループ、に取りまとめられます。
以下にモデル型グループにおける定数を示します:
- xml.parsers.expat.model.XML_CTYPE_ANY¶
モデル名で指定された要素は
ANYの内容モデルを持つと宣言されます。
- xml.parsers.expat.model.XML_CTYPE_CHOICE¶
指定されたエレメントはいくつかのオプションから選択できるようになっています;
(A | B | C)のような内容モデルで用いられます。
- xml.parsers.expat.model.XML_CTYPE_EMPTY¶
EMPTYであると宣言されている要素はこのモデル型を持ちます。
- xml.parsers.expat.model.XML_CTYPE_MIXED¶
The named element allows character data, optionally interspersed with the named children; this is used for content models such as
(#PCDATA)and(#PCDATA | A | B)*.
- xml.parsers.expat.model.XML_CTYPE_NAME¶
The model names a single element, as for
A.
- xml.parsers.expat.model.XML_CTYPE_SEQ¶
順々に続くようなモデルの系列を表すモデルがこのモデル型で表されます。
(A, B, C)のようなモデルで用いられます。
限定子グループにおける定数を以下に示します:
- xml.parsers.expat.model.XML_CQUANT_NONE¶
修飾子 (modifier) が指定されていません。従って
Aのように、厳密に一つだけです。
- xml.parsers.expat.model.XML_CQUANT_OPT¶
このモデルはオプションです:
A?のように、一つか全くないかです。
- xml.parsers.expat.model.XML_CQUANT_PLUS¶
このモデルは (
A+のように) 一つかそれ以上あります。
- xml.parsers.expat.model.XML_CQUANT_REP¶
このモデルは
A*のようにゼロ回以上あります。
Expat エラー定数¶
以下の定数は xml.parsers.expat.errors モジュールで提供されています。
これらの定数は、エラーが発生した際に送出される ExpatError 例外オブジェクトのいくつかの属性を解釈する上で便利です。
後方互換性の理由で、定数値は数字のエラー コード ではなくエラー メッセージ です。
属性を解釈するには code 属性と errors.codes[errors.XML_ERROR_CONSTANT_NAME] を比較します。
errors モジュールには以下の属性があります:
- xml.parsers.expat.errors.codes¶
文字列の記述をエラーコードに対応させる辞書です。
Added in version 3.2.
- xml.parsers.expat.errors.messages¶
数値的なエラーコードを文字列の記述に対応させる辞書です。
Added in version 3.2.
- xml.parsers.expat.errors.XML_ERROR_ASYNC_ENTITY¶
- xml.parsers.expat.errors.XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF¶
属性値中のエンティティ参照が、内部エンティティではなく外部エンティティを参照しました。
- xml.parsers.expat.errors.XML_ERROR_BAD_CHAR_REF¶
文字参照が、XML では正しくない (illegal) 文字を参照しました (例えば
0や '�')。
- xml.parsers.expat.errors.XML_ERROR_BINARY_ENTITY_REF¶
エンティティ参照が、記法 (notation) つきで宣言されているエンティティを参照したため、解析できません。
- xml.parsers.expat.errors.XML_ERROR_DUPLICATE_ATTRIBUTE¶
一つの属性が一つの開始タグ内に一度より多く使われています。
- xml.parsers.expat.errors.XML_ERROR_INCORRECT_ENCODING¶
- xml.parsers.expat.errors.XML_ERROR_INVALID_TOKEN¶
入力されたバイトが文字に適切に関連付けできない際に送出されます; 例えば、UTF-8 入力ストリームにおける NUL バイト (値
0) などです。
- xml.parsers.expat.errors.XML_ERROR_JUNK_AFTER_DOC_ELEMENT¶
空白以外の何かがドキュメント要素の後にあります。
- xml.parsers.expat.errors.XML_ERROR_MISPLACED_XML_PI¶
入力データの先頭以外の場所に XML 定義が見つかりました。
- xml.parsers.expat.errors.XML_ERROR_NO_ELEMENTS¶
The document contains no elements (XML requires all documents to contain exactly one top-level element).
- xml.parsers.expat.errors.XML_ERROR_NO_MEMORY¶
Expat が内部メモリを確保できませんでした。
- xml.parsers.expat.errors.XML_ERROR_PARAM_ENTITY_REF¶
パラメータエンティティの参照が、許可されていない場所で見つかりました。
- xml.parsers.expat.errors.XML_ERROR_PARTIAL_CHAR¶
入力に不完全な文字が見つかりました。
- xml.parsers.expat.errors.XML_ERROR_RECURSIVE_ENTITY_REF¶
エンティティ参照中に、同じエンティティへの別の参照が入っていました; おそらく違う名前で参照しているか、間接的に参照しています。
- xml.parsers.expat.errors.XML_ERROR_SYNTAX¶
詳細が特定されていない構文エラーが発生しました。
- xml.parsers.expat.errors.XML_ERROR_TAG_MISMATCH¶
終了タグが最も内側で開かれている開始タグに一致しません。
- xml.parsers.expat.errors.XML_ERROR_UNCLOSED_TOKEN¶
何らかの (開始タグのような) トークンが閉じられないまま、ストリームの終端や次のトークンに遭遇しました。
- xml.parsers.expat.errors.XML_ERROR_UNDEFINED_ENTITY¶
定義されていないエンティティへの参照が行われました。
- xml.parsers.expat.errors.XML_ERROR_UNKNOWN_ENCODING¶
ドキュメントのエンコードが Expat でサポートされていません。
- xml.parsers.expat.errors.XML_ERROR_UNCLOSED_CDATA_SECTION¶
CDATAセクションが閉じられていません。
- xml.parsers.expat.errors.XML_ERROR_EXTERNAL_ENTITY_HANDLING¶
- xml.parsers.expat.errors.XML_ERROR_NOT_STANDALONE¶
XML 文書は XML 宣言で "standalone" と宣言していましたが、パーサーはそうではないと判定しました。 また、
NotStandaloneHandlerが設定されていて、0を返しました。
- xml.parsers.expat.errors.XML_ERROR_UNEXPECTED_STATE¶
- xml.parsers.expat.errors.XML_ERROR_ENTITY_DECLARED_IN_PE¶
- xml.parsers.expat.errors.XML_ERROR_FEATURE_REQUIRES_XML_DTD¶
その操作を完了するにはDTDのサポートが必要ですが、ExpatがDTDのサポートをしない設定になっています。これは
xml.parsers.expatモジュールの標準的なビルドでは報告されません。
- xml.parsers.expat.errors.XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING¶
パースが始まったあとで動作の変更が要求されました。これはパースが開始される前にのみ変更可能です。(現在のところ)
UseForeignDTD()によってのみ送出されます。
- xml.parsers.expat.errors.XML_ERROR_UNBOUND_PREFIX¶
名前空間処理が有効な状態で、宣言されていないプレフィックスが見つかりました。
- xml.parsers.expat.errors.XML_ERROR_UNDECLARING_PREFIX¶
XML文書はプレフィックスに対応した名前空間宣言を削除しようとしました。
- xml.parsers.expat.errors.XML_ERROR_INCOMPLETE_PE¶
パラメータエンティティは不完全なマークアップを含んでいます。
- xml.parsers.expat.errors.XML_ERROR_XML_DECL¶
There was an error parsing the XML declaration.
- xml.parsers.expat.errors.XML_ERROR_TEXT_DECL¶
外部エンティティ中のテキスト宣言にエラーがあります。
- xml.parsers.expat.errors.XML_ERROR_PUBLICID¶
パブリックID中に許可されていない文字があります。
- xml.parsers.expat.errors.XML_ERROR_SUSPENDED¶
要求された操作は一時停止されたパーサで行われていますが、許可されていない操作です。このエラーは追加の入力を行なおうとしている場合、もしくはパーサが停止しようとしている場合にも送出されます。
- xml.parsers.expat.errors.XML_ERROR_NOT_SUSPENDED¶
一時停止していないパーサーを再開しようとしました。
- xml.parsers.expat.errors.XML_ERROR_ABORTED¶
Pythonアプリケーションには通知されません。
- xml.parsers.expat.errors.XML_ERROR_FINISHED¶
入力の解析が完了したパーサーに対して、許可されない操作を要求しました。 追加の入力を渡す操作や、パーサーを停止する操作などが該当します。
- xml.parsers.expat.errors.XML_ERROR_SUSPEND_PE¶
- xml.parsers.expat.errors.XML_ERROR_RESERVED_PREFIX_XML¶
予約済みの名前空間プレフィックス
xmlの宣言を解除するか、別の名前空間 URI に結び付けようとしました。
- xml.parsers.expat.errors.XML_ERROR_RESERVED_PREFIX_XMLNS¶
予約済みの名前空間プレフィックス
xmlnsを宣言するか、宣言を解除しようとしました。
- xml.parsers.expat.errors.XML_ERROR_RESERVED_NAMESPACE_URI¶
予約済みの名前空間プレフィックス
xmlまたはxmlnsの URI を、別の名前空間プレフィックスに結び付けようとしました。
- xml.parsers.expat.errors.XML_ERROR_INVALID_ARGUMENT¶
Pythonアプリケーションには通知されません。
- xml.parsers.expat.errors.XML_ERROR_NO_BUFFER¶
Pythonアプリケーションには通知されません。
- xml.parsers.expat.errors.XML_ERROR_AMPLIFICATION_LIMIT_BREACH¶
DTD とエンティティによる入力の増幅率が制限を超えました。
脚注