xml.parsers.expat --- Expat を使用した高速な XML 解析¶
注釈
If you need to parse untrusted or unauthenticated data, see XML security.
The xml.parsers.expat module is a Python interface to the Expat
non-validating XML parser. The module provides a single extension type,
xmlparser, that represents the current state of an XML parser. After
an xmlparser object has been created, various attributes of the object
can be set to handler functions. When an XML document is then fed to the
parser, the handler functions are called for the character data and markup in
the XML document.
このモジュールでは、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.
The xml.parsers.expat module contains two functions:
- xml.parsers.expat.ErrorString(errno)¶
与えられたエラー番号 errno を解説する文字列を返します。
- xml.parsers.expat.ParserCreate(encoding=None, namespace_separator=None, intern=None)¶
Creates and returns a new
xmlparserobject. encoding [1], if specified, must be a string naming the encoding used by the XML data. If it is given it will override the implicit or explicit encoding of the document.CPython 実装の詳細: Expat natively understands and processes UTF-8, UTF-16, UTF-16BE, UTF-16LE, ISO-8859-1, and US-ASCII. For other encodings (including aliases like Latin1 and ASCII) it falls back to Python. It supports most of 8-bit encodings and many multi-byte encodings like Shift_JIS, although only BMP characters (
U+0000-U+FFFF) are supported with non-native encodings (this restriction is also applied to aliases like UTF8). These restrictions only apply if encoding is not given.バージョン 3.16.0a0 (unreleased) で変更: Added support for multi-byte encodings.
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.GetSpecifiedAttributeCount()¶
Return the index just past the attributes given in the start tag. Attributes defaulted from the DTD follow the specified ones, so attributes at lower indices in the list passed to
StartElementHandlerwere given in the start tag. Each attribute takes two items in that list, its name and its value. Only meaningful inside aStartElementHandlercall, and only ifordered_attributesis true.Added in version 3.16.0a0 (unreleased).
- 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です。 flag の設定をしたら true を返します。
- 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)¶
警告
Calling
SetReparseDeferralEnabled(False)has security implications, as detailed below; please make sure to understand these consequences prior to using theSetReparseDeferralEnabledmethod.Expat 2.6.0 introduced a security mechanism called "reparse deferral" where instead of causing denial of service through quadratic runtime from reparsing large tokens, reparsing of unfinished tokens is now delayed by default until a sufficient amount of input is reached. Due to this delay, registered handlers may — depending of the sizing of input chunks pushed to Expat — no longer be called right after pushing new input to the parser. Where immediate feedback and taking over responsibility of protecting against denial of service from large tokens are both wanted, calling
SetReparseDeferralEnabled(False)disables reparse deferral for the current Expat parser instance, temporarily or altogether. CallingSetReparseDeferralEnabled(True)allows re-enabling reparse deferral.SetReparseDeferralEnabled()has been backported to some prior releases of CPython as a security fix. Check for availability usinghasattr()if used in code running across a variety of Python versions.Added in version 3.13.
- xmlparser.GetReparseDeferralEnabled()¶
Returns whether reparse deferral is currently enabled for the given Expat parser instance.
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.SetBillionLaughsAttackProtectionActivationThreshold()has been backported to some prior releases of CPython as a security fix. Check for availability usinghasattr()if used in code running across a variety of Python versions.注釈
Activation thresholds below 4 MiB are known to break support for DITA 1.3 payload and are hence not recommended.
Added in version 3.15.
- 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.SetBillionLaughsAttackProtectionMaximumAmplification()has been backported to some prior releases of CPython as a security fix. Check for availability usinghasattr()if used in code running across a variety of Python versions.注釈
The maximum amplification factor is only considered if the threshold that can be adjusted by
SetBillionLaughsAttackProtectionActivationThreshold()is exceeded.Added in version 3.15.
- 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.SetAllocTrackerActivationThreshold()has been backported to some prior releases of CPython as a security fix. Check for availability usinghasattr()if used in code running across a variety of Python versions.Added in version 3.15.
- 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.SetAllocTrackerMaximumAmplification()has been backported to some prior releases of CPython as a security fix. Check for availability usinghasattr()if used in code running across a variety of Python versions.注釈
The maximum amplification factor is only considered if the threshold that can be adjusted by
SetAllocTrackerActivationThreshold()is exceeded.Added in version 3.15.
xmlparser オブジェクトは次のような属性を持ちます:
- xmlparser.buffer_size¶
buffer_textが真の時に使われるバッファのサイズです。この属性に新しい整数値を代入することで違うバッファサイズにできます。サイズが変えられるときにバッファはフラッシュされます。
- xmlparser.buffer_text¶
Setting this to true causes the
xmlparserobject to buffer textual content returned by Expat to avoid multiple calls to theCharacterDataHandler()callback whenever possible. This can improve performance substantially since Expat normally breaks character data into chunks at every line ending. This attribute is false by default, and may be changed at any time. Note that when it is false, data that does not contain newlines may be chunked too.
- 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)¶
Called for character data. This will be called for normal character data, CDATA marked content, and ignorable whitespace. Applications which must distinguish these cases can use the
StartCdataSectionHandler,EndCdataSectionHandler, andElementDeclHandlercallbacks to collect the required information. Note that the character data may be chunked even if it is short and so you may receive more than one call toCharacterDataHandler(). Set thebuffer_textinstance attribute toTrueto avoid that.
- 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)¶
名前空間宣言を含んでいたエレメントの終了タグに到達したときに呼び出されます。このハンドラは、要素に関する名前空間宣言ごとに、
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 handler functions
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)、名前、そして子のタプル。子のタプルは単に内容モデルを記述したものです。
The values of the first two fields are constants defined in the
xml.parsers.expat.model module. These constants can be collected in two
groups: the model type group and the quantifier group.
以下にモデル型グループにおける定数を示します:
- 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 エラー定数¶
The following constants are provided in the xml.parsers.expat.errors
module. These constants are useful in interpreting some of the attributes of
the ExpatError exception objects raised when an error has occurred.
Since for backwards compatibility reasons, the constants' value is the error
message and not the numeric error code, you do this by comparing its
code attribute with
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文書が "standalone" だと宣言されており
NotStandaloneHandlerが設定され0が返されているにもかかわらず、パーサは "standalone" ではないと判別しました。
- 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¶
An operation was requested that requires DTD support to be compiled in, but Expat was configured without DTD support. This should never be reported by a standard build of the
xml.parsers.expatmodule.
- 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¶
An attempt was made to undeclare reserved namespace prefix
xmlor to bind it to another namespace URI.
- xml.parsers.expat.errors.XML_ERROR_RESERVED_PREFIX_XMLNS¶
An attempt was made to declare or undeclare reserved namespace prefix
xmlns.
- xml.parsers.expat.errors.XML_ERROR_RESERVED_NAMESPACE_URI¶
An attempt was made to bind the URI of one the reserved namespace prefixes
xmlandxmlnsto another namespace prefix.
- 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¶
The limit on input amplification factor (from DTD and entities) has been breached.
- xml.parsers.expat.errors.XML_ERROR_NOT_STARTED¶
The parser was tried to be stopped or suspended before it started.
Added in version 3.14.
脚注