Skip to content

Instantly share code, notes, and snippets.

@Cartman0
Created April 5, 2016 11:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cartman0/87d2d00c5d64c66778f20d1d056e76c7 to your computer and use it in GitHub Desktop.
Save Cartman0/87d2d00c5d64c66778f20d1d056e76c7 to your computer and use it in GitHub Desktop.
Dive Into Python3 12章メモ(XML)
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"metadata": {
"toc": "true"
},
"cell_type": "markdown",
"source": "# Table of Contents\n <p><div class=\"lev1\"><a href=\"#12章-XML-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>12章 XML</a></div><div class=\"lev2\"><a href=\"#飛び込む-1.1\"><span class=\"toc-item-num\">1.1&nbsp;&nbsp;</span>飛び込む</a></div><div class=\"lev2\"><a href=\"#5分間短期集中XML入門コース-1.2\"><span class=\"toc-item-num\">1.2&nbsp;&nbsp;</span>5分間短期集中XML入門コース</a></div><div class=\"lev2\"><a href=\"#Atomフィードの構造-1.3\"><span class=\"toc-item-num\">1.3&nbsp;&nbsp;</span>Atomフィードの構造</a></div><div class=\"lev2\"><a href=\"#XMLをパースする-1.4\"><span class=\"toc-item-num\">1.4&nbsp;&nbsp;</span>XMLをパースする</a></div><div class=\"lev3\"><a href=\"#要素はリスト-1.4.1\"><span class=\"toc-item-num\">1.4.1&nbsp;&nbsp;</span>要素はリスト</a></div><div class=\"lev3\"><a href=\"#属性は辞書-1.4.2\"><span class=\"toc-item-num\">1.4.2&nbsp;&nbsp;</span>属性は辞書</a></div><div class=\"lev2\"><a href=\"#XML文書の中からノードを検索する-1.5\"><span class=\"toc-item-num\">1.5&nbsp;&nbsp;</span>XML文書の中からノードを検索する</a></div><div class=\"lev2\"><a href=\"#LXML-を使ってさらに踏み込む-1.6\"><span class=\"toc-item-num\">1.6&nbsp;&nbsp;</span>LXML を使ってさらに踏み込む</a></div><div class=\"lev2\"><a href=\"#XMLを生成する-1.7\"><span class=\"toc-item-num\">1.7&nbsp;&nbsp;</span>XMLを生成する</a></div><div class=\"lev2\"><a href=\"#壊れたXMLをパースする-1.8\"><span class=\"toc-item-num\">1.8&nbsp;&nbsp;</span>壊れたXMLをパースする</a></div><div class=\"lev2\"><a href=\"#参考リンク-1.9\"><span class=\"toc-item-num\">1.9&nbsp;&nbsp;</span>参考リンク</a></div>"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "- [Dive Into Python3 1章メモ](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/d54093a99b9254c81bf1123adacbc48a/raw/eedc90bbbfc14e259854f2e739fffeec4cb4d8f7/DiveIntoPython3_01.ipynb)\n- [Dive Into Python3 2章メモ(ネイティブデータ型)](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/988b51d8482ad9ade835bb07efdffb38/raw/784cf276b7cebe254e59f09dcea6f09eea760d38/DiveIntoPython3_02.ipynb)\n- [Dive Into Python3 3章メモ(内包表記)](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/183ec6f6c835f621106f7c27d215290a/raw/bd7677946d6400bbe6acd257df7fb9c5976c3320/DiveIntoPython3_03.ipynb)\n- [Dive Into Python3 4章メモ(文字列)](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/bb974f82e8a3fc74ac82c3c2a5b1a4f9/raw/63a80011c9391b451108c1a4dc804ec5ff125f34/DiveIntoPython3_04.ipynb)\n- [Dive Into Python3 5章メモ(正規表現)](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/b834807a0dabb1c458b87be2f333a5ca/raw/37d6f25f67e017a569e1f0b60a9fcbe49d50515f/DiveIntoPython3_05.ipynb?flush_cache=true)\n- [Dive Into Python3 6章メモ(クロージャとジェネレータ)](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/a8998f8f88c5578271495ada56cc4809/raw/4e9b8ef3543016a710f905215693694acd703549/DiveIntoPython3_06.ipynb?flush_cache=true)\n- [Dive Into Python3 7章メモ(クラスとイテレータ)](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/8eb511c3b2aa6cadad6f6d49666c9db2/raw/60863d1ce1c1e9e4cb336ad79a0e252807beb87c/DiveIntoPython3_07.ipynb?flush_cache=true)\n- [Dive Into Python3 8章メモ(高度なイテレータ)](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/9ed3037cbdac59af53c20c125aed806e/raw/46ee3c71d72ab7ee665cf0c10f8717734632b462/DiveIntoPython3_08.ipynb?flush_cache=true)\n- [Dive Into Python3 9章メモ(ユニットテスト)](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/1833320ab55ae5ea660ce0c635483d26/raw/46034833206366c8011594cbea2efce90168d54b/DiveIntoPython3_09.ipynb?flush_cache=true)\n- [Dive Into Python3 10章メモ(リファクタリング)](http://nbviewer.jupyter.org/gist/Cartman0/0c0af20eb95236da4da9547258fe2bb3?flush_cache=true)\n- [Dive Into Python3 11章メモ(ファイル)](http://nbviewer.jupyter.org/gist/Cartman0/152eacd23b793ecd3dbf5f706ae33e92?flush_cache=true)"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "# 12章 XML"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## 飛び込む"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`xml` の一般的な用例として、\nブログやフォーラム、その他の頻繁に更新されるウェブサイトの最新記事をリストアップするのに使われる「フィード」がある。\n有名なブログ用ソフトウェアのほとんどは、\nフィードを生成して、新しい記事やスレッドや投稿が公開されるたびにフィードの内容を更新する機能を備えている。\n皆さんがそのブログのフィードを「購読」すれば、\nそのブログの更新を追うことができ、\nGoogle Readerのような専用の「フィードアグリゲータ」を使うことで多数のブログを追いかけることもできる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "この章で扱っていくxmlデータがある。\nこのデータはフィード — 具体的に言うと**Atomフィード** というもの。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "```\n<?xml version='1.0' encoding='utf-8'?>\n<feed xmlns='http://www.w3.org/2005/Atom' xml:lang='en'>\n <title>dive into mark</title>\n <subtitle>currently between addictions</subtitle>\n <id>tag:diveintomark.org,2001-07-29:/</id>\n <updated>2009-03-27T21:56:07Z</updated>\n <link rel='alternate' type='text/html' href='http://diveintomark.org/'/>\n <link rel='self' type='application/atom+xml' href='http://diveintomark.org/feed/'/>\n <entry>\n <author>\n <name>Mark</name>\n <uri>http://diveintomark.org/</uri>\n </author>\n <title>Dive into history, 2009 edition</title>\n <link rel='alternate' type='text/html'\n href='http://diveintomark.org/archives/2009/03/27/dive-into-history-2009-edition'/>\n <id>tag:diveintomark.org,2009-03-27:/archives/20090327172042</id>\n <updated>2009-03-27T21:56:07Z</updated>\n <published>2009-03-27T17:20:42Z</published>\n <category scheme='http://diveintomark.org' term='diveintopython'/>\n <category scheme='http://diveintomark.org' term='docbook'/>\n <category scheme='http://diveintomark.org' term='html'/>\n <summary type='html'>Putting an entire chapter on one page sounds\n bloated, but consider this &amp;mdash; my longest chapter so far\n would be 75 printed pages, and it loads in under 5 seconds&amp;hellip;\n On dialup.</summary>\n </entry>\n <entry>\n <author>\n <name>Mark</name>\n <uri>http://diveintomark.org/</uri>\n </author>\n <title>Accessibility is a harsh mistress</title>\n <link rel='alternate' type='text/html'\n href='http://diveintomark.org/archives/2009/03/21/accessibility-is-a-harsh-mistress'/>\n <id>tag:diveintomark.org,2009-03-21:/archives/20090321200928</id>\n <updated>2009-03-22T01:05:37Z</updated>\n <published>2009-03-21T20:09:28Z</published>\n <category scheme='http://diveintomark.org' term='accessibility'/>\n <summary type='html'>The accessibility orthodoxy does not permit people to\n question the value of features that are rarely useful and rarely used.</summary>\n </entry>\n <entry>\n <author>\n <name>Mark</name>\n </author>\n <title>A gentle introduction to video encoding, part 1: container formats</title>\n <link rel='alternate' type='text/html'\n href='http://diveintomark.org/archives/2008/12/18/give-part-1-container-formats'/>\n <id>tag:diveintomark.org,2008-12-18:/archives/20081218155422</id>\n <updated>2009-01-11T19:39:22Z</updated>\n <published>2008-12-18T15:54:22Z</published>\n <category scheme='http://diveintomark.org' term='asf'/>\n <category scheme='http://diveintomark.org' term='avi'/>\n <category scheme='http://diveintomark.org' term='encoding'/>\n <category scheme='http://diveintomark.org' term='flv'/>\n <category scheme='http://diveintomark.org' term='GIVE'/>\n <category scheme='http://diveintomark.org' term='mp4'/>\n <category scheme='http://diveintomark.org' term='ogg'/>\n <category scheme='http://diveintomark.org' term='video'/>\n <summary type='html'>These notes will eventually become part of a\n tech talk on video encoding.</summary>\n </entry>\n</feed>\n```"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## 5分間短期集中XML入門コース"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`xml` は、階層構造をもつデータを記述するための汎用的な手法。\nxml文書 (document) は1つ以上の要素 (element)を含んでおり、\nこれらの要素は開始タグと終了タグによって区切られる。\n以下は、完全なxml文書だ:"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "```\n<foo> 1\n</foo> 2\n```\n\n1. foo要素の開始タグになる。\n\n2. foo要素の開始タグに対応する終了タグ。\n文章や数学やコードにおいて括弧を釣り合わせるのと同じように、すべての開始タグは対応する終了タグによって閉じられなければならない。\n"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "要素はどんな深さにまでネストされていても良い。\nfoo要素の内部にあるbar要素は、fooの子 (child) ないし下位要素 (subelement) と呼ばれる。\n\n```\n<foo>\n <bar></bar>\n</foo>\n```"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "あらゆるxml文書において、一番初めの要素はルート要素 (root element) と呼ばれる。\n`xml` はルート要素を1つだけ持つことができる。\n以下は2つのルート要素を持っているので、xml文書ではない。\n\n```\n<foo></foo>\n<bar></bar>\n```"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "要素は属性 (`attributes`) を持つことができる。\n属性というのは名前と値のペアだ。\n属性は、開始タグのなかで、空白で区切られて列挙される。\n同じ属性名を1つの要素の中で繰り返し使うことは許されず、属性値はクォート文字で囲む必要がある。\nクォートは、シングルクォートとダブルクォートのどちらでもかまわない。\n\n```\n<foo lang='en'> # 1\n <bar id='papayawhip' lang=\"fr\"></bar> # 2\n</foo>\n```\n1. \tfoo要素は、langという名前の1つの属性を持っている。このlang属性の値はenになる\n\n2. bar要素は、`id` および `lang` という名前の2つの属性を持っている。\nlang属性の値はfrになっているが、\nこれがfoo要素のlang属性と衝突することは絶対にない。\n個々の要素の属性は、その要素に固有のもの。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "要素が2つ以上の属性を持っているとき、それらの属性の並び順は意味を持たない。\n要素の属性というのは、Pythonの辞書のような順序づけされていないキーと値の集合だととらえられる。\nなお、個々の要素の上に定義できる属性の数に制限はない。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "要素はテキスト内容 (text content) を持つことができる。\n\n```\n<foo lang='en'>\n <bar lang='fr'>PapayaWhip</bar>\n</foo>\n```"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "テキストも子も持たない要素は空要素 (empty element) になる。\n\n```\n<foo></foo>\n```"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "空要素を書くための省略表現がある。\n/を開始タグに付けることで、\n終了タグを完全に省略することができる。\n先ほどのxml文書は、代わりに次のように書くことができる:\n\n```\n<foo/>\n```"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "Pythonの関数を異なるモジュールに定義できるのと同様に、\nxml要素も異なる名前空間 (namespace)に定義することができる。\n名前空間は普通はURLのような見た目をしている。\nデフォルトの名前空間を定義するには、`xmlns`宣言を使用する。\n名前空間の宣言は属性に似ているが、異なる目的を持っている。\n\n```\n<feed xmlns='http://www.w3.org/2005/Atom'> 1\n <title>dive into mark</title> 2\n</feed>\n```\n\n1. feed要素は、`http://www.w3.org/2005/Atom`名前空間の中にある。\n2. title要素も、`http://www.w3.org/2005/Atom`名前空間の中にある。\n名前空間の宣言は、それが定義された要素に加えて、すべての子要素にも影響する。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`xmlns:prefix`宣言を使うと、\n宣言した名前空間を接頭辞 (prefix)に関連づけることができる。\nその場合、その名前空間にある各要素は、明示的に接頭辞を付けて宣言しなければならなくなる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "```\n<atom:feed xmlns:atom='http://www.w3.org/2005/Atom'> 1\n <atom:title>dive into mark</atom:title> 2\n</atom:feed>\n```\n\n1. feed要素は、`http://www.w3.org/2005/Atom`名前空間の中にある。\n2. title要素も、`http://www.w3.org/2005/Atom`名前空間の中にある。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "xmlパーサにとっては、先に示した2つのxml文書は同一。\n名前空間 + 要素名 = xmlの同一性。\n接頭辞は名前空間を参照するためだけに存在しているので、\n接頭辞の名前 (`atom:`) 自体は意味を持たない。\n名前空間が一致し、要素名が一致し、属性の有無と値が一致し、\n各々の要素のテキスト内容が一致していれば、xml文書は同一。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "xml文書の最初の行(つまりルート要素の前)には文字コード情報を入れることができる。\n\n```\n<?xml version='1.0' encoding='utf-8'?>\n```"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## Atomフィードの構造"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "頻繁に更新されるコンテンツを持ったウェブサイトなら何でもいい。\nこのようなサイトとしては例えば、CNN.comがある。\nこのサイトは、\n- タイトル (“CNN.com”) と、\n- サブタイトル (“Breaking News, U.S., World, Weather, Entertainment & Video News”)、\n- 最終更新日 (“updated 12:43 p.m.EDT, Sat May 16, 2009”) と、\n- 異なる時間に投稿された記事のリストを持っている。\n\nそれぞれの記事もまた、タイトルと、最初に投稿された日時(公開後に訂正されたり誤字が修正された場合は最終更新日時も)と、固有のURLを持っている。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`Atom`形式は、このすべての情報を標準形式で記録するように設計されている。\nブログとCNN.comは、デザイン・対象領域・読者の点で大きく異なっているが、\n両者とも同じような基本構造を持っている。\nCNN.comはタイトルを持ち、ブログもタイトルを持つ。\nCNN.comは記事を公開し、ブログも記事を公開する。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "トップレベルにあるのはルート要素だ。\nこの要素(`http://www.w3.org/2005/Atom`名前空間のfeed要素)はどのAtomフィードでも同じになる。\n\n```\n<feed xmlns='http://www.w3.org/2005/Atom' 1\n xml:lang='en'> 2\n```\n1. \t`http://www.w3.org/2005/Atom` はAtomの名前空間だ。\n2.\tどんな要素にも`xml:lang`属性を加えることができる。\nこの属性は、その要素とその子要素の言語を宣言する。\nこの例では、`xml:lang`属性はルート要素で一度だけ宣言されているので、\nフィード全体が英語で書かれていることがわかる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`Atom`フィードの中にはフィード自身に関する情報もいくつか存在している。\nこれらは、ルートレベルの`feed`要素の子供として宣言されている。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "```\n<feed xmlns='http://www.w3.org/2005/Atom' xml:lang='en'>\n <title>dive into mark</title> 1\n <subtitle>currently between addictions</subtitle> 2\n <id>tag:diveintomark.org,2001-07-29:/</id> 3\n <updated>2009-03-27T21:56:07Z</updated> 4\n <link rel='alternate' type='text/html' href='http://diveintomark.org/'/> 5\n```\n\n1. フィードのタイトルは「dive into mark」\n2. フィードのサブタイトルは「currently between addictions」になる。\n3. どのフィードにも識別子(id)をつける必要があり、\nこの識別子はネット上においてユニークでなければならない。\nこれの作り方については「[RFC 4151](http://www.ietf.org/rfc/rfc4151.txt)」に書いてある。\n4. このフィードが最後に更新されたのは2009年3月27日の21:56 GMT。\n通常、これは最新記事の最終変更日時と等しい。\n5. このlink要素はテキスト内容を持っていないが、\n3つの属性rel, type, hrefを持っている。relの値はこのリンクの種類を伝えている。rel='alternate'というのは、\nこれがこのフィードの代替表現へのリンクだということを意味している。\n`type='text/html'`属性は、これがhtmlページへのリンクだということを意味している。\nそして、リンクのターゲットは`href`属性で与えられている。\n\n\n- [RFC 4151 日本語訳](http://pentan.info/doc/rfc/j4151.html)"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "このサイトは、 “dive into mark“ という名前のサイトのフィードであり、\nそのサイトは `http://diveintomark.org/` で利用でき、\nそのサイトの最終更新日は2009年3月27日だということがわかる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "一部のxml文書では要素の順序が意味を持つことがあるが、\n「`Atom`フィード」では要素の順序は意味を持たない。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "フィード自体に関するメタデータの後は、最新記事のリストになっている。\n一つ一つの記事は次のように表されている:"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "```\n<entry>\n <author> 1\n <name>Mark</name>\n <uri>http://diveintomark.org/</uri>\n </author>\n <title>Dive into history, 2009 edition</title> 2\n <link rel='alternate' type='text/html' 3\n href='http://diveintomark.org/archives/2009/03/27/dive-into-history-2009-edition'/>\n <id>tag:diveintomark.org,2009-03-27:/archives/20090327172042</id> 4\n <updated>2009-03-27T21:56:07Z</updated> 5\n <published>2009-03-27T17:20:42Z</published>\n <category scheme='http://diveintomark.org' term='diveintopython'/> 6\n <category scheme='http://diveintomark.org' term='docbook'/>\n <category scheme='http://diveintomark.org' term='html'/>\n <summary type='html'>Putting an entire chapter on one page sounds 7\n bloated, but consider this &amp;mdash; my longest chapter so far\n would be 75 printed pages, and it loads in under 5 seconds&amp;hellip;\n On dialup.</summary>\n</entry>\n```\n\n1. `author`要素は、誰がこの記事を書いたのかを伝えている。\nそいつはMarkという名前で、`http://diveintomark.org/` \nに行けばぶらついている彼に会うことができる(このURLはフィードのメタデータにある代替リンクと同じだが、かならずしも同じである必要はない。\n実際、多くのウェブログは、自分のウェブサイトを持つ執筆者が何人か集まって書いている)。\n\n2. `title`要素は記事のタイトル “Dive into history, 2009 edition” を表している。\n\n3. フィードレベルの代替リンクと同様に、このlink要素は記事のhtml版のアドレスを示している。\n4. フィードと同様に、エントリには固有の識別子(id) が必要。\n5. エントリは2つの日付を持っている: \n - 初めて公開された日時(published)と、\n - 最終更新日時(updated)。\n\n6. エントリは任意の数のカテゴリを持つことができる。\nこの記事はdiveintopython、docbook、htmlに分類されている。\n\n7. `summary`要素は記事の短い要約を与える(ここには示されていないが、フィードに記事の全文を含めたい場合のためのcontent要素も存在する)。\nこのsummary要素にはAtom特有のtype='html'属性が含まれており、\nこれはこの要約がプレーンテキストではなくhtmlで書かれていることを示している。\nなぜなら、この要約には、`html`特有の実体参照(&mdash;と&hellip;)が含まれているから。\nこれらの記号は、そのままの形ではなく、\n“—” と “……” に変換した上で表示しなくてはならない。\n\n8. 最後に、entry要素の終了タグがこの記事のメタデータの終わりを伝えている。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## XMLをパースする"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "Pythonで`xml`文書をパースする方法は何種類かある。\nこれまで伝統的に用いられてきた`dom`パーサと`sax`パーサも使えるが、\nここでは`ElementTree`と呼ばれる別のライブラリを使う。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "examples/feed.xml\n\n```\n<?xml version='1.0' encoding='utf-8'?>\n<feed xmlns='http://www.w3.org/2005/Atom' xml:lang='en'>\n <title>dive into mark</title>\n <subtitle>currently between addictions</subtitle>\n <id>tag:diveintomark.org,2001-07-29:/</id>\n <updated>2009-03-27T21:56:07Z</updated>\n <link rel='alternate' type='text/html' href='http://diveintomark.org/'/>\n <entry>\n <author>\n <name>Mark</name>\n <uri>http://diveintomark.org/</uri>\n </author>\n <title>Dive into history, 2009 edition</title>\n <link rel='alternate' type='text/html'\n href='http://diveintomark.org/archives/2009/03/27/dive-into-history-2009-edition'/>\n <id>tag:diveintomark.org,2009-03-27:/archives/20090327172042</id>\n <updated>2009-03-27T21:56:07Z</updated>\n <published>2009-03-27T17:20:42Z</published>\n <category scheme='http://diveintomark.org' term='diveintopython'/>\n <category scheme='http://diveintomark.org' term='docbook'/>\n <category scheme='http://diveintomark.org' term='html'/>\n <summary type='html'>Putting an entire chapter on one page sounds\n bloated, but consider this &amp;mdash; my longest chapter so far\n would be 75 printed pages, and it loads in under 5 seconds&amp;hellip;\n On dialup.</summary>\n </entry>\n <entry>\n <author>\n <name>Mark</name>\n <uri>http://diveintomark.org/</uri>\n </author>\n <title>Accessibility is a harsh mistress</title>\n <link rel='alternate' type='text/html'\n href='http://diveintomark.org/archives/2009/03/21/accessibility-is-a-harsh-mistress'/>\n <id>tag:diveintomark.org,2009-03-21:/archives/20090321200928</id>\n <updated>2009-03-22T01:05:37Z</updated>\n <published>2009-03-21T20:09:28Z</published>\n <category scheme='http://diveintomark.org' term='accessibility'/>\n <summary type='html'>The accessibility orthodoxy does not permit people to\n question the value of features that are rarely useful and rarely used.</summary>\n </entry>\n <entry>\n <author>\n <name>Mark</name>\n </author>\n <title>A gentle introduction to video encoding, part 1: container formats</title>\n <link rel='alternate' type='text/html'\n href='http://diveintomark.org/archives/2008/12/18/give-part-1-container-formats'/>\n <id>tag:diveintomark.org,2008-12-18:/archives/20081218155422</id>\n <updated>2009-01-11T19:39:22Z</updated>\n <published>2008-12-18T15:54:22Z</published>\n <category scheme='http://diveintomark.org' term='asf'/>\n <category scheme='http://diveintomark.org' term='avi'/>\n <category scheme='http://diveintomark.org' term='encoding'/>\n <category scheme='http://diveintomark.org' term='flv'/>\n <category scheme='http://diveintomark.org' term='GIVE'/>\n <category scheme='http://diveintomark.org' term='mp4'/>\n <category scheme='http://diveintomark.org' term='ogg'/>\n <category scheme='http://diveintomark.org' term='video'/>\n <summary type='html'>These notes will eventually become part of a\n tech talk on video encoding.</summary>\n </entry>\n</feed>\n```"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`ElementTree`ライブラリはPython標準ライブラリの一部であり、\n`xml.etree.ElementTree` に含まれている。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "import xml.etree.ElementTree as etree ",
"execution_count": 1,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`ElementTree`ライブラリのメインのエントリポイントは `parse()`関数であり、\nこの関数はファイル名、もしくはファイルライクオブジェクトを引数に取る。\nこの関数は文書全体を一度にパースするが、\n\nメモリが限られている場合は、xml文書をインクリメンタルにパースする方法も用意されている。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "tree = etree.parse('examples/feed.xml')\ntree",
"execution_count": 2,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "<xml.etree.ElementTree.ElementTree at 0x1c1ab399ef0>"
},
"metadata": {},
"execution_count": 2
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`parse()`関数は文書全体を表すオブジェクトを返す。\nこのオブジェクトはルート要素ではない。\nルート要素の参照を取得するには、`getroot()`メソッドを呼び出す。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "root = tree.getroot()",
"execution_count": 3,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "ルート要素は、\n`http://www.w3.org/2005/Atom`名前空間にある`feed`要素になる。\nこのオブジェクトの文字列表現は重要なポイントを強調している。\n\nすなわち、xml要素というのは名前空間とタグ名(ローカル名とも呼ばれる)の組み合わせになる。この文書のすべてのタグはAtomの名前空間の中にあるので、ルート要素は{`http://www.w3.org/2005/Atom`}feedと表現される。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "root",
"execution_count": 4,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "<Element '{http://www.w3.org/2005/Atom}feed' at 0x000001C1AB2D0EF8>"
},
"metadata": {},
"execution_count": 4
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`ElementTree` は、xml要素を`{namespace}localname` と表現する。\nこの形式は、ElementTree apiの様々な場所で見たり使ったりすることになる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "### 要素はリスト"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "ElementTree APIでは、要素はリストのように振る舞う。\nそのリストのアイテムは、その要素の子要素になっている。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "ルート要素は `{http://www.w3.org/2005/Atom}feed` になっている。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "root.tag",
"execution_count": 5,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "'{http://www.w3.org/2005/Atom}feed'"
},
"metadata": {},
"execution_count": 5
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "ルート要素の「長さ」は子要素の数になる。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "len(root)",
"execution_count": 6,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "8"
},
"metadata": {},
"execution_count": 6
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "要素自体をイテレータとして使って、すべての子要素を取得することもできる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "このfeedでは、8つの子要素がある。\n最初の5つにはフィードのメタデータがすべて入っており\n(title, subtitle, id, updated, link)、\nその後に3つのentry要素が続いている。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "for child in root:\n print(child)",
"execution_count": 7,
"outputs": [
{
"output_type": "stream",
"text": "<Element '{http://www.w3.org/2005/Atom}title' at 0x000001C1AB39ED68>\n<Element '{http://www.w3.org/2005/Atom}subtitle' at 0x000001C1AB39EDB8>\n<Element '{http://www.w3.org/2005/Atom}id' at 0x000001C1AB39EEA8>\n<Element '{http://www.w3.org/2005/Atom}updated' at 0x000001C1AB39EEF8>\n<Element '{http://www.w3.org/2005/Atom}link' at 0x000001C1AB39EF98>\n<Element '{http://www.w3.org/2005/Atom}entry' at 0x000001C1AB3A5048>\n<Element '{http://www.w3.org/2005/Atom}entry' at 0x000001C1AB3A54F8>\n<Element '{http://www.w3.org/2005/Atom}entry' at 0x000001C1AB3A58B8>\n",
"name": "stdout"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "子要素のリストは直接の子だけを含んでいる。\n\n各々の `entry`要素はさらに子要素を持っているが、それらはこのリストには含まれていない。それらは各々の`entry`の子のリストには含まれるだろうが、feedの子供のリストには含まれない。\nネストされている要素を、たとえどれだけ深くネストされていても、\n見つけ出す方法は存在する。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "### 属性は辞書"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`xml` は要素だけで成り立っているわけではない。\n個々の要素には、それぞれ属性をつけることができる。\n特定の要素への参照を取得すれば、\nその要素の属性をPythonの辞書として簡単に取得することができる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`attrib`プロパティは、この要素の属性の辞書になる。\n元々のマークアップは\n`<feed xmlns='http://www.w3.org/2005/Atom' xml:lang='en'>` である。\n`xml:接頭辞` は、すべてのxml文書が宣言なしに使用できる組み込みの名前空間を参照している。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "root.attrib",
"execution_count": 8,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "{'{http://www.w3.org/XML/1998/namespace}lang': 'en'}"
},
"metadata": {},
"execution_count": 8
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "今回の場合、5番目の子(インデックスが0から始まるリストの[4])はlink要素になる。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "root[4]",
"execution_count": 9,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "<Element '{http://www.w3.org/2005/Atom}link' at 0x000001C1AB39EF98>"
},
"metadata": {},
"execution_count": 9
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "link要素は3つの属性を持っている: `href`、`type`、`rel`。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "root[4].attrib",
"execution_count": 10,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "{'href': 'http://diveintomark.org/', 'rel': 'alternate', 'type': 'text/html'}"
},
"metadata": {},
"execution_count": 10
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "4番目の子(インデックスが0から始まるリストの[3])はupdated要素になる。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "root[3]",
"execution_count": 11,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "<Element '{http://www.w3.org/2005/Atom}updated' at 0x000001C1AB39EEF8>"
},
"metadata": {},
"execution_count": 11
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "updated要素は属性を持っていないので、.attribは単なる空の辞書になる。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "root[3].attrib",
"execution_count": 12,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "{}"
},
"metadata": {},
"execution_count": 12
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## XML文書の中からノードを検索する"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "ここまでは、xml文章を「トップダウン」方式で扱ってきた。\nルート要素から始めて、その子要素を取得して、という過程を文書全体で繰り返していく手法だった。\nしかし、xmlの多くの用途では、特定の要素を検索することが必要になる。\n`ElementTree` は、もちろんそれを行うことができる。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "import xml.etree.ElementTree as etree\ntree = etree.parse('examples/feed.xml')",
"execution_count": 13,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "findall()メソッドは、指定されたクエリにマッチする子要素を見つけ出す。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "root.findall('{http://www.w3.org/2005/Atom}entry')",
"execution_count": 14,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "[<Element '{http://www.w3.org/2005/Atom}entry' at 0x000001C1AB3A5048>,\n <Element '{http://www.w3.org/2005/Atom}entry' at 0x000001C1AB3A54F8>,\n <Element '{http://www.w3.org/2005/Atom}entry' at 0x000001C1AB3A58B8>]"
},
"metadata": {},
"execution_count": 14
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "すべての要素(ルート要素だけでなく子要素も)が `findall()` メソッドを持っている。\nこのメソッドはクエリにマッチするすべての要素を子要素の中から見つけ出す。\n**このクエリは要素の子供だけを検索する**。\nルート要素feedは、feedという名前の子を持っていないので、このクエリは空のリストを返す。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "root.findall('{http://www.w3.org/2005/Atom}feed')",
"execution_count": 15,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "[]"
},
"metadata": {},
"execution_count": 15
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "この文書の中にauthor要素は3つ存在する(それぞれのentryにある)。\nしかし、これらのauthor要素はルート要素の直接の子供ではなく、「孫」(文字通り、子要素の子要素)にあたる。すべてのネストレベルのauthor要素を探したいのであれば、もちろんそれは可能だが、クエリの形式は少し違ったものになる。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "root.findall('{http://www.w3.org/2005/Atom}author')",
"execution_count": 16,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "[]"
},
"metadata": {},
"execution_count": 16
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "(`etree.parse()`関数から返される)treeオブジェクトには、\nルート要素のメソッドがいくつかそのまま移植されている。\nこのメソッドを実行すると、\n`tree.getroot().findall()` を呼び出したときとまったく同じ結果がえられる。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "import xml.etree.ElementTree as etree\ntree = etree.parse('examples/feed.xml')\ntree.findall('{http://www.w3.org/2005/Atom}entry')",
"execution_count": 17,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "[<Element '{http://www.w3.org/2005/Atom}entry' at 0x000001C1AB3B2278>,\n <Element '{http://www.w3.org/2005/Atom}entry' at 0x000001C1AB3B2728>,\n <Element '{http://www.w3.org/2005/Atom}entry' at 0x000001C1AB3B2AE8>]"
},
"metadata": {},
"execution_count": 17
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "これは `tree.getroot().findall('{http://www.w3.org/2005/Atom}author')` \nのショートカットに過ぎず、「ルート要素の子供のauthor要素を探す」ことを意味しているので空辞書を返す。\n`author`要素はルート要素の子供でななく、entry要素の子供になっている。\n従って、このクエリはマッチする要素を一つも返さない。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "tree.findall('{http://www.w3.org/2005/Atom}author')",
"execution_count": 18,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "[]"
},
"metadata": {},
"execution_count": 18
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "最初にマッチした要素を返す `find()`メソッドもある。\nこのメソッドは、マッチするのは1つだけだと考えられる場合や、\n複数のマッチがあったとしても、その1つ目にしか興味がないときに便利。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "entries = tree.findall('{http://www.w3.org/2005/Atom}entry')\nlen(entries)",
"execution_count": 19,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "3"
},
"metadata": {},
"execution_count": 19
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`find()`メソッドは、`ElementTree` のクエリを引数に取り、最初にマッチする要素を返す。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "title_element = entries[0].find('{http://www.w3.org/2005/Atom}title') \ntitle_element.text",
"execution_count": 20,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "'Dive into history, 2009 edition'"
},
"metadata": {},
"execution_count": 20
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "このエントリにfooという要素は存在しないので、これはNoneを返す。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "foo_element = entries[0].find('{http://www.w3.org/2005/Atom}foo')\nfoo_element\ntype(foo_element)",
"execution_count": 21,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "NoneType"
},
"metadata": {},
"execution_count": 21
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "find()メソッドには、「ワナ」が存在する。\nブール値のコンテクストにおいて、ElementTreeの要素オブジェクトは子要素を含んでいないときに(つまりlen(element)が0のときに)Falseと評価されるのだ。\n\nしたがって、`if element.find('...')` は、`find()`メソッドがマッチする要素を見つけたかどうかをテストしているのではなく、マッチした要素が子要素を持つかどうかをテストしている。\n\n`find()`メソッドが要素を返したかどうかテストしたいなら、\n`if element.find('...') is not None` を使う。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "子孫要素(つまり、子供・孫・任意のネストレベルの要素)を検索する方法は実際に存在する。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "このクエリ`//{http://www.w3.org/2005/Atom}link` は先ほどの例と非常に似ているが、クエリの先頭に2つのスラッシュが付いている。\n\nこれら2つのスラッシュ「`//`」は、\n「直接の子供だけを探さないでほしい。ネストレベルに関係なく、すべての要素を探したい」ということを意味している。\nしたがって、結果は1つだけではなく、4つのlink要素のリストになる。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "tree.findall('{http://www.w3.org/2005/Atom}link') # feedの中のlink 1つを返す",
"execution_count": 22,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "[<Element '{http://www.w3.org/2005/Atom}link' at 0x000001C1AB3B2228>]"
},
"metadata": {},
"execution_count": 22
}
]
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "all_links = tree.findall('.//{http://www.w3.org/2005/Atom}link') # entryの中のlink(3つ) も含まれる\nall_links",
"execution_count": 23,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "[<Element '{http://www.w3.org/2005/Atom}link' at 0x000001C1AB3B2228>,\n <Element '{http://www.w3.org/2005/Atom}link' at 0x000001C1AB3B24A8>,\n <Element '{http://www.w3.org/2005/Atom}link' at 0x000001C1AB3B2908>,\n <Element '{http://www.w3.org/2005/Atom}link' at 0x000001C1AB3B2C28>]"
},
"metadata": {},
"execution_count": 23
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "1つ目の結果はルート要素の直接の子要素。\nこの属性から分かるとおり、これはフィードが表しているウェブサイトのhtml版を指すフィードレベルの代替リンク。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "all_links[0].attrib",
"execution_count": 24,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "{'href': 'http://diveintomark.org/', 'rel': 'alternate', 'type': 'text/html'}"
},
"metadata": {},
"execution_count": 24
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "他の3つはそれぞれエントリレベルの代替リンクになる。\n各々のentryは単一のlink子要素を持っており、クエリの先頭に2つのスラッシュによって、このクエリはこれらすべてを探し出す。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "all_links[1].attrib",
"execution_count": 25,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "{'href': 'http://diveintomark.org/archives/2009/03/27/dive-into-history-2009-edition',\n 'rel': 'alternate',\n 'type': 'text/html'}"
},
"metadata": {},
"execution_count": 25
}
]
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "all_links[2].attrib",
"execution_count": 26,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "{'href': 'http://diveintomark.org/archives/2009/03/21/accessibility-is-a-harsh-mistress',\n 'rel': 'alternate',\n 'type': 'text/html'}"
},
"metadata": {},
"execution_count": 26
}
]
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "all_links[3].attrib",
"execution_count": 27,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "{'href': 'http://diveintomark.org/archives/2008/12/18/give-part-1-container-formats',\n 'rel': 'alternate',\n 'type': 'text/html'}"
},
"metadata": {},
"execution_count": 27
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`ElementTreeのfindall()`メソッドは強力な機能だと言えるが、\nクエリ言語には少し分かりづらい部分がある。\nこの点については公式に「XPath式を限定的にサポートする」と説明されている。XPathはW3C標準のxml用クエリ言語。\n\n`ElementTree` のクエリ言語は基本的な検索には十分なくらいXPathに似ているが、\nすでにXPathを知っている人にとっては、十分に煩わしい程度の違いもある。\n今度は、XPathを完全にサポートするように`ElementTree` APIを拡張した、サードパーティ製の\nxmlライブラリを見てみる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## LXML を使ってさらに踏み込む"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`lxml` は広く使われている `libxml2` パーサの上に構築されたオープンソースのサードパーティ製ライブラリ。\nこのライブラリは、100%の互換性を持たせる形で\n`ElementTree` apiを実装しており、\nさらにそこへ `XPath 1.0` のフルサポートと細かな改良を付け加えている。\nWindowsにはインストーラが用意されている。\nLinuxユーザは、できるだけ各ディストリビューションに付属している`yum` や`apt-get` などのツールを使って、リポジトリからコンパイル済バイナリを取得するようにしてほしい。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "anaconda を使っていれば、\n\n```\nconda install lxml\n```\n\nでインストールできる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "インポートすれば、あとは組み込みの `ElementTree`ライブラリと同じapiが使える。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "from lxml import etree",
"execution_count": 28,
"outputs": []
},
{
"metadata": {
"collapsed": true
},
"cell_type": "markdown",
"source": "`parse()`関数:ElementTreeと同じように使える。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "tree = etree.parse('examples/feed.xml')\ntree",
"execution_count": 29,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "<lxml.etree._ElementTree at 0x1c1ab3b7188>"
},
"metadata": {},
"execution_count": 29
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`getroot()`メソッド:これも `ElementTree` と同じように使える。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "root = tree.getroot()\nroot",
"execution_count": 30,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "<Element {http://www.w3.org/2005/Atom}feed at 0x1c1ab414288>"
},
"metadata": {},
"execution_count": 30
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`findall()`メソッドも同じ。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "root.findall('{http://www.w3.org/2005/Atom}entry')",
"execution_count": 31,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "[<Element {http://www.w3.org/2005/Atom}entry at 0x1c1ab414408>,\n <Element {http://www.w3.org/2005/Atom}entry at 0x1c1ab4143c8>,\n <Element {http://www.w3.org/2005/Atom}entry at 0x1c1ab414448>]"
},
"metadata": {},
"execution_count": 31
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "巨大なxml文書を扱う場合、`lxml` の処理は組み込みの `ElementTree`ライブラリよりもはるかに高速。\n\nElementTreeのapiだけを使っていて、かつ利用できるライブラリの中で最も速い実装を使いたいのであれば、\nまずはlxmlをインポートしてみて、\nエラーが出るようなら組み込みの `ElementTree` にフォールバックするといい。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "try:\n from lxml import etree\nexcept ImportError:\n import xml.etree.ElementTree as etree\n\netree",
"execution_count": 32,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "<module 'lxml.etree' from 'C:\\\\Miniconda3\\\\lib\\\\site-packages\\\\lxml\\\\etree.pyd'>"
},
"metadata": {},
"execution_count": 32
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": " `lxml` は `ElementTree` より高速なだけではない。\n`lxml` の `findall()`メソッドはもっと複雑な式をサポートしている。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "import lxml.etree\ntree = lxml.etree.parse('examples/feed.xml')",
"execution_count": 33,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "このクエリは、xml文書全体を対象として、\nhref属性を持つAtom名前空間の要素をすべて探し出す。\nクエリの先頭にある`//`は、「(ルート要素の子供だけではなく)あらゆる要素を探索する」ことを意味する。\n\n`{http://www.w3.org/2005/Atom}` は、「Atomの名前空間の要素だけ」を意味する。\n`*` は「どんなローカル名を持つ要素でもいい」ことを意味する。\nそして、`[@href]` は「href属性を持っている」ことを意味する。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "tree.findall('//{http://www.w3.org/2005/Atom}*[@href]')",
"execution_count": 34,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "[<Element {http://www.w3.org/2005/Atom}link at 0x1c1ab418148>,\n <Element {http://www.w3.org/2005/Atom}link at 0x1c1ab418488>,\n <Element {http://www.w3.org/2005/Atom}link at 0x1c1ab418448>,\n <Element {http://www.w3.org/2005/Atom}link at 0x1c1ab414d48>]"
},
"metadata": {},
"execution_count": 34
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "このクエリは、`http://diveintomark.org/` を値とする `href`属性を持つ `Atom`要素を全て探し出す。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": " tree.findall(\"//{http://www.w3.org/2005/Atom}*[@href='http://diveintomark.org/']\")",
"execution_count": 35,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "[<Element {http://www.w3.org/2005/Atom}link at 0x1c1ab418148>]"
},
"metadata": {},
"execution_count": 35
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "ちょっとした文字列フォーマットを施した上で(これをしないと、\n合成したクエリはばかばかしいほど長くなってしまう)、\n\nこのクエリは、Atomのuri要素を子要素として持つAtomのauthor要素を検索する。これは、1つ目と2つ目のentry要素の中にある2つのauthor要素だけを返す。最後のentryにあるauthorはnameだけを含んでおり、uriは含んでいない。"
},
{
"metadata": {
"collapsed": false,
"trusted": true,
"scrolled": true
},
"cell_type": "code",
"source": "NS = '{http://www.w3.org/2005/Atom}'\ntree.findall('//{NS}author[{NS}uri]'.format(NS=NS)) ",
"execution_count": 36,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "[<Element {http://www.w3.org/2005/Atom}author at 0x1c1ab418848>,\n <Element {http://www.w3.org/2005/Atom}author at 0x1c1ab4188c8>]"
},
"metadata": {},
"execution_count": 36
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`lxml` がどのように `XPath` をサポートしているのかは示す。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "import lxml.etree\ntree = lxml.etree.parse('examples/feed.xml')",
"execution_count": 37,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "名前空間の付いた要素の上でXPathのクエリを実行するには、名前空間の接頭辞のマッピングを定義する必要がある。これは単なるPythonの辞書。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "NSMAP = {'atom': 'http://www.w3.org/2005/Atom'} ",
"execution_count": 38,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "これがXPathのクエリ。\n\nこのXPath式は、accessibilityという値を持つterm属性を含んだ(Atomの名前空間の)category要素を探し出す。\nしかし、実際に返されるのは `category`要素のリストではない。\n\nクエリ文字列の一番最後の\n`/..`という部分は、「見つけた`category`要素の親要素を返してくれ」という意味だ。\nつまり、この XPathクエリを実行すると、\n`<category term='accessibility'>` という子要素を持つすべての要素が返される。"
},
{
"metadata": {
"collapsed": false,
"trusted": true,
"scrolled": true
},
"cell_type": "code",
"source": "entries = tree.xpath(\"//atom:category[@term='accessibility']/..\", namespaces=NSMAP)",
"execution_count": 39,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "この `xpath()`関数は、`ElementTree`オブジェクトのリストを返す。\nこの文書には、term属性の値が`accessibility` である`category`要素は1つだけ存在する。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "entries",
"execution_count": 40,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "[<Element {http://www.w3.org/2005/Atom}entry at 0x1c1ab418208>]"
},
"metadata": {},
"execution_count": 40
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`XPath` 式は常に要素のリストを返すわけではない。\n厳密に言えば、パースしたxml文書のdomに含まれているのは要素ではなく、\nノードだからだ。\nノードの種類に応じて、ノードの内容は要素であったり、属性であったり、テキスト内容であったりする。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "entry = entries[0]",
"execution_count": 41,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "XPathクエリを実行することで得られるのはノードのリスト。\n\n実際、このクエリはテキストノードのリストを返しており、\nその中身は現在の要素の子 (./) の `title`要素 (`atom:title`) のテキスト内容 (`text()`) になっている。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "entry.xpath('./atom:title/text()', namespaces=NSMAP) ",
"execution_count": 42,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "['Accessibility is a harsh mistress']"
},
"metadata": {},
"execution_count": 42
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## XMLを生成する"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "Python がサポートするのは、既存のxml文書をパースすることだけに留まらない。\n`xml`文書をゼロから作成することもできる。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "import xml.etree.ElementTree as etree",
"execution_count": 43,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "新しい要素を作るには、`Element`クラスをインスタンス化すればいい。\n最初の引数として要素名(名前区間 + ローカル名)を渡す。\nこの文はAtomの名前区間にあるfeed要素を作成するが、これが新しい文書のルート要素になる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "新しく作成した要素に属性を追加するには、属性名と属性値の辞書をattrib引数で渡せばいい。\n属性名は `ElementTree` の標準形式`{namespace}localname` で書かなければいけないことに注意"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": " new_feed = etree.Element('{http://www.w3.org/2005/Atom}feed',\n attrib={'{http://www.w3.org/XML/1998/namespace}lang': 'en'})",
"execution_count": 44,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "ElementTreeのtostring()関数を使えば、任意の要素(とその子要素)をいつでもシリアライズできる。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "print(etree.tostring(new_feed))",
"execution_count": 45,
"outputs": [
{
"output_type": "stream",
"text": "b'<ns0:feed xmlns:ns0=\"http://www.w3.org/2005/Atom\" xml:lang=\"en\" />'\n",
"name": "stdout"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": " ElementTreeが名前空間付きのxml要素をシリアライズする方法は、技術的には正確だが最適なものではない。\nこの章のはじめに載せたxml文書のサンプルでは、「デフォルトの名前空間」(`xmlns='http://www.w3.org/2005/Atom'`) を定義していた。\n \n このようにデフォルトの名前空間を定義することは、Atomフィードのようにすべての要素が同じ名前空間にある文書にとっては有用だ。なぜなら、名前区間を一度だけ定義すれば、各々の要素はローカル名 ( `<feed>、<link>、<entry>` ) だけで宣言することができるため。\n 他の名前空間の要素を宣言するのでなければ、接頭辞をつける必要はまったく無い。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "xmlパーサは、デフォルト名前空間をもつxml文書と、接頭辞のついたxml文書の違いを「理解しない」。次のシリアライズのdomは:\n\n```\n<ns0:feed xmlns:ns0='http://www.w3.org/2005/Atom' xml:lang='en'/>\n```\n\n次のシリアライズのdomと同一:\n\n```\n<feed xmlns='http://www.w3.org/2005/Atom' xml:lang='en'/>\n```"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "実用上問題となる違いは、\n2番目のシリアライズの方が何文字か短いということだけだ。\nサンプルフィード中の開始タグと終了タグすべてにns0:接頭辞を付けると、\n開始タグごとに4文字 × 79タグ + 名前空間の宣言に使う4文字で、合計320文字になる。\n\nUTF-8エンコーディングを使うとすると、\nこの余分な文字だけで320バイトになる(gzip圧縮すると増分は21バイトになるが、それでも21バイトは21バイトだ)。\nだから何なのかと思うかもしれないが、Atomフィードのように、\n更新されるたびに何千回もダウンロードされるようなものについては、\n数バイト減らすだけでもすぐに大きな差につながりうる"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "組み込みのElementTreeでは、名前空間のついた要素のシリアライズを細かく制御することはできないが、lxmlを使えばそれができる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "準備として、名前空間のマッピングを辞書として定義する。\n辞書の値は名前空間で、辞書のキーは使用したい接頭辞。\n**接頭辞として `None` を使うと、結果的にデフォルト名前区間を定義することになる**。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "import lxml.etree\nNSMAP = {None: 'http://www.w3.org/2005/Atom'} ",
"execution_count": 46,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "要素を作成するときに `nsmap`引数(この引数はlxmlにしかない)を渡せば、\n`lxml`は定義した接頭辞を考慮してくれる。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "new_feed = lxml.etree.Element('feed', nsmap=NSMAP)",
"execution_count": 47,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "このシリアライズはAtomの名前空間をデフォルトの名前空間として定義しており、\n名前空間の接頭辞を使わずにfeed要素を宣言している。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "print(lxml.etree.tounicode(new_feed)) ",
"execution_count": 48,
"outputs": [
{
"output_type": "stream",
"text": "<feed xmlns=\"http://www.w3.org/2005/Atom\"/>\n",
"name": "stdout"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`set()`メソッドを使えば任意の要素にいつでも属性を追加できる。\n\nこのメソッドは2つの引数をとる: \n- ElementTreeの標準形式での属性名と、\n- 属性の値\n\n(このメソッドはlxml固有のものではない。\nこの例でlxmlに特有な部分は、シリアライズ出力の名前空間の接頭辞を制御するためのnsmap引数だけだ)。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "new_feed.set('{http://www.w3.org/XML/1998/namespace}lang', 'en') ",
"execution_count": 49,
"outputs": []
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "print(lxml.etree.tounicode(new_feed))",
"execution_count": 50,
"outputs": [
{
"output_type": "stream",
"text": "<feed xmlns=\"http://www.w3.org/2005/Atom\" xml:lang=\"en\"/>\n",
"name": "stdout"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "子要素も簡単に作成できる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "既存の要素の子要素を作るには、`SubElement`クラスをインスタンス化すればいい。\n要求される引数は\n- 親要素(この場合はnew_feed)と\n- 新しい要素の名前だけ。\n\nこの子要素は、親要素の名前空間のマッピングを継承するので、名前空間や接頭語を再び宣言する必要はない。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "属性の辞書を渡すこともできる。キーは属性名で、値は属性値になる。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "title = lxml.etree.SubElement(new_feed, 'title', attrib={'type':'html'}) ",
"execution_count": 51,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "新しい`title`要素は `Atom`の名前空間の中に作られ、\n`feed`要素の子として挿入されている。\n`title`要素はテキスト内容や自身の子供を持たないので、\nlxmlはこれを(/>ショートカットを使った)空要素としてシリアライズする。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "print(lxml.etree.tounicode(new_feed))",
"execution_count": 52,
"outputs": [
{
"output_type": "stream",
"text": "<feed xmlns=\"http://www.w3.org/2005/Atom\" xml:lang=\"en\"><title type=\"html\"/></feed>\n",
"name": "stdout"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "要素のテキスト内容を設定するには、単にその要素の.textプロパティを設定すればいい。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "title.text = 'dive into &hellip;'",
"execution_count": 53,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "ここで `title`要素はテキスト内容と共にシリアライズされている。\n小なり記号やアンパサンドを含んだテキスト内容は、\nシリアライズ時にエスケープされる必要がある。\nlxmlはこのエスケープを自動的に処理してくれる。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "print(lxml.etree.tounicode(new_feed))",
"execution_count": 54,
"outputs": [
{
"output_type": "stream",
"text": "<feed xmlns=\"http://www.w3.org/2005/Atom\" xml:lang=\"en\"><title type=\"html\">dive into &amp;hellip;</title></feed>\n",
"name": "stdout"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "シリアライズ処理に `“pretty printing”` を適用することもできる。\nこれは、終了タグの後ろや、子要素を持つがテキスト内容を持たない要素の開始タグの後ろに改行を挿入する。\n\n専門用語で言えば、lxmlは「意味のない空白 (insignificant whitespace)」を加えることによって、結果をより読みやすいものにする。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "print(lxml.etree.tounicode(new_feed, pretty_print=True))",
"execution_count": 55,
"outputs": [
{
"output_type": "stream",
"text": "<feed xmlns=\"http://www.w3.org/2005/Atom\" xml:lang=\"en\">\n <title type=\"html\">dive into &amp;hellip;</title>\n</feed>\n\n",
"name": "stdout"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "xmlを生成するための別のサードパーティ製ライブラリである [xmlwitch](https://pypi.python.org/pypi/xmlwitch/0.2.1) を調べてみるのもよい。このライブラリはxmlの生成コードをより読みやすくするために、with文を広く活用している。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## 壊れたXMLをパースする"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "xmlの仕様によれば、\n仕様に準拠したxmlパーサは「厳格なエラー処理」を行わなくてはならないものとされている。\nつまり、xml文書の中に何か一つでも整形式性エラーが見つかれば、すぐさま処理を停止して例外を送出しなくてはならない。\n整形式性エラーとは、開始タグと終了タグのミスマッチや、未定義の実体、不正なUnicode文字列といったものであり、他にも数々の難解な規則が存在している。\n\nこれは `html` のようなほかの一般的なデータ形式とは対照的 — ブラウザは、htmlタグを閉じ忘れたり、\n属性値の中でアンパサンド (&) をエスケープし忘れても、ウェブページのレンダリングを中断することはない\n(htmlにエラー処理が定義されていないというのは良くある誤解。\nhtmlのエラー処理は実は非常に明確に定義されているのだが、「エラーが見つかりしだい処理を停止する」よりも著しく複雑)。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "一部の人々は、xmlが厳格なエラー処理を採用したのは間違いだったと考えている。\n実際問題として、「整形式性」の概念は思ったよりも扱いにくいものであり、とりわけ、ウェブ上で公開され、httpを通して送信される(Atomフィード)のようなxml文書についてはそれが言える。厳格なエラー処理は1997年に標準化されており、xmlは規格としては既に成熟していると言えるが、調査は一貫として、Web上で公開されている少なからぬ割合のAtomフィードに整形式エラーが存在していることを示している。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "理論的にも実用的にもxmlはエラーがあろうともパースされるべきだと考えている人もいる。\nつまり、整形式性エラーを見つけたとしても、即座に処理を停止しない。\nもしこの考え方に共感を覚えるなら、lxmlを使えばこの方式でパースすることができる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "ここに壊れたxml文書の断片がある。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "examples/feed-broken.xml:\n\n```\n<?xml version='1.0' encoding='utf-8'?>\n<feed xmlns='http://www.w3.org/2005/Atom' xml:lang='en'>\n <title>dive into &hellip;</title>\n...\n</feed>\n```"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`&hellip;` という実体参照は、xmlでは定義されていないので(htmlでは定義されている)、\nこれはエラーになる。この壊れたフィードをデフォルトの設定でパースしようとすると、エラーになる。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "%tb\nimport lxml.etree\ntree = lxml.etree.parse('examples/feed-broken.xml')",
"execution_count": 56,
"outputs": [
{
"output_type": "stream",
"text": "No traceback available to show.\n",
"name": "stderr"
},
{
"output_type": "error",
"ename": "XMLSyntaxError",
"evalue": "Entity 'hellip' not defined, line 3, column 28 (<string>)",
"traceback": [
"\u001b[1;36m File \u001b[1;32m\"<string>\"\u001b[1;36m, line \u001b[1;32munknown\u001b[0m\n\u001b[1;31mXMLSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m Entity 'hellip' not defined, line 3, column 28\n"
]
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "整形式性のエラーを無視して、この破損したxml文書を読み込むには、カスタムのxmlパーサを作る必要がある。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "カスタムのパーサを作るには、`lxml.etree.XMLParser`クラスをインスタンス化すればいい。\nこのクラスは様々な名前付き引数を取ることができる。\n\nここでrecover引数を `True` に設定すると、xmlパーサは整形式性のエラーから「回復する」ために最善を尽くすようになる。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "parser = lxml.etree.XMLParser(recover=True) \nparser",
"execution_count": 57,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "<lxml.etree.XMLParser at 0x1c1ab4022a8>"
},
"metadata": {},
"execution_count": 57
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "カスタムパーサを使ってxml文書をパースするには、\n2番目の引数として `parser`オブジェクトを `parse()`関数に渡せばいい。\nlxmlは未定義の`&hellip;` 実体に関する例外を送出していないことに注意。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "tree = lxml.etree.parse('examples/feed-broken.xml', parser)\ntree",
"execution_count": 58,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "<lxml.etree._ElementTree at 0x1c1ab418748>"
},
"metadata": {},
"execution_count": 58
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "パーサは遭遇した整形式性エラーのログを記録する\n(実は、パーサがエラーから回復するように設定されていない場合も、エラーはログに記録されている)。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "parser.error_log",
"execution_count": 59,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "examples/feed-broken.xml:3:28:FATAL:PARSER:ERR_UNDECLARED_ENTITY: Entity 'hellip' not defined"
},
"metadata": {},
"execution_count": 59
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "未定義の `&hellip;`実体をどう扱えばよいのか分からないので、\nパーサは端的にこの部分を無視する。`title`要素のテキスト内容は`'dive into '`になる。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "title = tree.findall('{http://www.w3.org/2005/Atom}title')[0]\ntitle.text",
"execution_count": 60,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "'dive into '"
},
"metadata": {},
"execution_count": 60
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "シリアライズ結果から分かるように、\n`&hellip;`実体は取り込まれていない。\nパースの時点で無視された。"
},
{
"metadata": {
"collapsed": false,
"trusted": true,
"scrolled": true
},
"cell_type": "code",
"source": "print(lxml.etree.tounicode(tree))",
"execution_count": 61,
"outputs": [
{
"output_type": "stream",
"text": "<feed xmlns=\"http://www.w3.org/2005/Atom\" xml:lang=\"en\">\n <title>dive into </title>\n...\n</feed>\n",
"name": "stdout"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "xmlパーサの「回復」処理には**相互運用性の保証はない**。\n別のパーサはhtmlの&hellip;を認識することにして、これを&amp;hellip;で置き換えるかもしれない。これは「より良い」のだろうか? おそらくそうだ。\n\nこれは「より正しい」のだろうか? いや違う、これらは両方とも等しく誤りなのだ。(XMLの仕様に従った)正しい振る舞いは即座に処理を停止した上で例外を送出すること。\nもしそうしないことに決めたのなら、それは自分の責任で行わなければならない。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## 参考リンク"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "- [Dive Into Pyton3 12章 XML](http://diveintopython3-ja.rdy.jp/xml.html)\n- [xml.dom — 文書オブジェクトモデル (DOM) API python doc](http://docs.python.jp/3.5/library/xml.dom.html)\n- [xml.etree.ElementTree — ElementTree XML API python doc](http://docs.python.jp/3.5/library/xml.etree.elementtree.html)\n- [lxml - XML and HTML with Python](http://lxml.de/)\n- [xmlwitch](https://pypi.python.org/pypi/xmlwitch/0.2.1)"
}
],
"metadata": {
"language_info": {
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.1",
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python"
},
"toc": {
"toc_number_sections": true,
"toc_threshold": "6",
"toc_window_display": false,
"toc_cell": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3",
"language": "python"
},
"gist": {
"id": "",
"data": {
"description": "Dive Into Python3 12章メモ(XML)",
"public": true
}
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment