はじめに
XML 文書の構造
XML 文書は、XML 宣言から始まります。要素は、正しくネストされ、閉じられなければなりません。追加のメタデータを提供するのが、属性です。名前の衝突を避ける XML の名前空間を宣言するのが、xmlns です。
<?xml version="1.0" encoding="UTF-8"?>
<!-- This is a comment -->
<bookstore xmlns="https://example.com/books">
<book id="b1" category="fiction">
<title lang="en">The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
<price currency="USD">12.99</price>
</book>
<book id="b2" category="programming">
<title lang="en">XML Guide</title>
<author>John Doe</author>
<price currency="USD">29.99</price>
</book>
</bookstore>XML 宣言
プログローグの最初の行であるのが、XML 宣言です。「version」が必須で(1.0 か 1.1)、「encoding」は UTF-8 をデフォルトとし、「standalone」が、外部の DTD の宣言が必要かどうかパーサーに伝えます。
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!-- version is required; encoding and standalone are optional -->
<!-- encoding defaults to UTF-8 -->
<!-- standalone="yes" means no external markup declarations -->
<root>
<child>text</child>
</root>コメントと処理命令
コメントは <!-- --> を使い、ネストや内側の「--」を含むことはできません。xml-stylesheet のような処理命令(PI)が、アプリ固有の情報をパーサーへ渡します。PI は、<?target data?> を使います。
<?xml version="1.0"?>
<!-- a comment: ignored by the parser, cannot contain -- -->
<?xml-stylesheet type="text/xsl" href="style.xsl"?>
<root>
<!-- comments can span
multiple lines -->
<item>data</item>
</root>Well-formed な XML
Well-formed とは:1 つのルート要素、正しいネスト、閉じられたすべてのタグ、引用された属性、重複のない属性です。パース可能であるためには、文書が well-formed でなければなりません。(DTD/Schema に対する)validity はオプションです。
<!-- WELL-FORMED: single root, properly nested, closed -->
<root>
<a>
<b>text</b>
</a>
</root>
<!-- NOT well-formed: two roots, overlapping tags -->
<!-- <a><b></a></b> -->
<!-- <x></x><y></y> (no single root) -->
<!-- All attributes must be quoted -->
<item id='1' type="x"/>XML プロローグと空白
プロローグには、XML 宣言とオプションの DOCTYPE が含まれます。パーサーに空白を保たせるのが、xml:space='preserve' で、通常の処理を許すのが「default」です。要素の間の空白は、一般に重要ではありません。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE root SYSTEM "root.dtd">
<root xml:space="preserve">
<item> spaced text </item>
<item xml:space="default"> trimmed </item>
</root>CDATA の概観
CDATA のセクションは、パーサーがマークアップとして解釈すべきでないテキストを印付けます。CDATA の内側では、<、>、& のような文字がエスケープを必要としません。ネストできず、リテラルの「]]>」を含められないのが、CDATA です。
<?xml version="1.0"?>
<root>
<code><![CDATA[
if (a < b && c > d) {
console.log("no escaping needed: < > & ");
}
]]></code>
</root>要素と属性
要素対属性
メタデータ(id、タイプ、フラグ)に適するのが、属性です。構造か繰り返される値を持つデータに適するのが、要素です。属性は要素ごとに 1 回現れ、ネストした構造を保持できません。厳密な規則はなく — 最も重要なのが、一貫性です。
<!-- Attributes: metadata/identifiers; Elements: data -->
<person id="p1">
<name>Alice</name>
<age>30</age>
</person>
<!-- vs. putting everything in attributes -->
<person id="p1" name="Alice" age="30"/>
<!-- Rule of thumb: use elements for data you display,
attributes for IDs, types, and metadata -->空の要素
コンテンツを持たないのが、空の要素です。<tag></tag> の省略形であるのが、自己閉じの形式 <tag/> です。読みやすさと XHTML の互換性のためのスタイルの慣例であるのが、「/>」の前のスペースです。
<!-- Three equivalent empty-element forms -->
<br></br>
<br/>
<br />
<!-- empty element with attributes -->
<img src="logo.png" alt="Logo" width="200" height="100"/>
<!-- self-closing with namespace -->
<xlink:link xmlns:xlink="http://www.w3.org/1999/xlink" href="#sec1"/>ネストした要素
階層的にネストし、逆順で閉じられなければならないのが、要素です — 重なり合えません。構造を表現するのが、ネストです。深くネストしたツリーは有効ですが、読みやすさとパースのパフォーマンスを損ない得ます。
<library>
<section name="fiction">
<book>
<title>Book A</title>
<authors>
<author>Author 1</author>
<author>Author 2</author>
</authors>
</book>
</section>
</library>
<!-- WRONG: tags must not overlap -->
<!-- <a><b></a></b> -->属性の値と引用符
単一か二重の引用符で引用されなければならないのが、属性の値です。二重引用符の値の内側の二重引用符は、" としてエスケープされなければなりません。属性は要素ごとに 1 回しか現れ得ません — 繰り返される値には、子の要素を使いましょう。
<!-- Both single and double quotes are allowed -->
<item id="q1" name='quick'/>
<msg text="He said "hi""/>
<msg text='She said 'hi''/>
<!-- attribute values MUST be quoted -->
<!-- <item id=q1/> is NOT well-formed -->
<!-- an attribute can appear at most once per element -->
<point x="1" y="2" z="3"/>デフォルトと固定の属性
DTD の属性の宣言がサポートするもの:#REQUIRED(現れなければならない)、#IMPLIED(オプション)、#FIXED(定数の値)、リテラルのデフォルトです。#FIXED の属性は、常に宣言された値に等しくなければならず、さもなければ文書が invalid です。
<!-- In a DTD, attributes can have defaults -->
<!ATTLIST item
type CDATA "standard"
status CDATA #REQUIRED
version CDATA #FIXED "1.0"
note CDATA #IMPLIED>
<item status="active"/>
<!-- 'type' defaults to "standard", 'version' is fixed,
'note' is optional (#IMPLIED) -->要素の命名規則
文字かアンダースコアで始まり、文字、数字、ハイフン、アンダースコア、ドットを含み得るのが、要素名です。「xml」(大小を問わず)で始められません。大文字小文字を区別するのが、XML です。そのため、<Tag> と <tag> が異なります。
<!-- Names: start with a letter or underscore,
continue with letters, digits, hyphens, underscores, dots -->
<my-element>ok</my-element>
<my.element>ok</my.element>
<my_element>ok</my_element>
<_private>ok</_private>
<x-1>ok</x-1>
<!-- NOT allowed: starting with a digit or 'xml', containing spaces -->
<!-- <2way/> -->
<!-- <my element/> -->
<!-- <XmlTag/> (names are case-sensitive; 'xml' prefix is reserved) -->名前空間
デフォルトの名前空間
宣言された要素とすべての接頭辞なしの子孫に適用されるのが、デフォルトの名前空間(xmlns=URI)です。上書きされない限り、子の要素がそれを継承します。デフォルトの名前空間を決して使わないのが、属性です。
<?xml version="1.0"?>
<table xmlns="http://www.w3.org/1999/xhtml">
<tr>
<td>Cell content</td>
<td>More content</td>
</tr>
</table>
<!-- All elements without a prefix use the default namespace -->名前空間の接頭辞
xmlns:prefix=URI で宣言され、prefix:element として使われるのが、名前空間の接頭辞です。単なるエイリアスであるのが接頭辞であり — 同一性に重要なのが、URI だけです。大文字小文字を区別するのが、接頭辞です。
<?xml version="1.0"?>
<root xmlns:bk="https://example.com/books"
xmlns:au="https://example.com/authors">
<bk:book bk:id="b1">
<au:author au:name="Jane Doe"/>
<bk:title>XML Guide</bk:title>
</bk:book>
</root>複数の名前空間
多くの名前空間を混ぜられるのが、単一の文書です。各接頭辞を一度宣言し(通常はルートで)、再利用しましょう。要素上での名前空間の宣言が、その要素とその子孫に適用されます。
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<m:GetPrice xsi:type="xsd:string"
xmlns:m="https://example.com/pricing">
<m:Item>Apples</m:Item>
</m:GetPrice>
</soap:Body>
</soap:Envelope>名前空間のスコープ
現れた要素とその子孫にスコープされるのが、名前空間の宣言です。子の内側での再宣言が、そのサブツリーのための親の接頭辞のマッピングを上書きします。子が閉じられた後で回復されるのが、元のマッピングです。
<?xml version="1.0"?>
<root xmlns:a="http://a.example">
<a:item>A</a:item>
<child xmlns:a="http://b.example">
<!-- here 'a' is REBOUND to the b.example URI -->
<a:item>B</a:item>
</child>
<!-- outside child, 'a' is back to a.example -->
<a:item>A again</a:item>
</root>よくある名前空間
これらの URI は、よく知られた識別子であり、取得されなければならない URL ではありません。schema-instance の属性(type、nil、schemaLocation)を提供するのが、xsi の名前空間です。XSD、XSL、SVG、SOAP、Atom、そして Dublin Core(dc)が、それぞれ標準の URI を持ちます。
<!-- Frequently used namespace URIs -->
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd = "http://www.w3.org/2001/XMLSchema"
xmlns:xsl = "http://www.w3.org/1999/XSL/Transform"
xmlns:svg = "http://www.w3.org/2000/svg"
xmlns:html = "http://www.w3.org/1999/xhtml"
xmlns:soap = "http://schemas.xmlsoap.org/soap/envelope/"
xmlns:atom = "http://www.w3.org/2005/Atom"
xmlns:dc = "http://purl.org/dc/elements/1.1/"XSD のターゲット名前空間
スキーマが定義する要素の名前空間であるのが、そのスキーマの targetNamespace です。ローカルで宣言された要素が、ターゲットの名前空間にあることを意味するのが、elementFormDefault='qualified' です。「この名前空間」のための慣例であるのが、tns の接頭辞です。
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="https://example.com/orders"
xmlns:tns="https://example.com/orders"
elementFormDefault="qualified">
<xs:element name="order" type="tns:OrderType"/>
<xs:complexType name="OrderType">
<xs:sequence>
<xs:element name="item" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:schema>CDATA とエンティティ
定義済みのエンティティ
5 つのエンティティを XML が事前定義します:<(<)、>(>)、&(&)、'(')、"(")です。& は必ずエスケープされなければならず(CDATA のないテキストでも)、< はタグの開始としてでなければエスケープされ、引用符は主に属性で重要です。
<?xml version="1.0"?>
<root>
<lt>less than: <</lt>
<gt>greater than: ></gt>
<amp>ampersand: &</amp>
<apos>apostrophe: '</apos>
<quot>quote: "</quot>
<!-- < > & ' " are the 5 built-in entities -->
</root>文字参照
Unicode のコードポイントを使うのが、文字参照です:© が、©(10 進)か ©(16 進)です。要素のテキストと属性の値で機能し、エンコーディングに影響されません。任意の Unicode の文字を表現できます。
<?xml version="1.0" encoding="UTF-8"?>
<root>
<decimal>© 2024 Company</decimal>
<hex>© 2024 Company</hex>
<euro>Price: €10</euro>
<emoji>Smile: 😀</emoji>
</root>
<!-- &#NNN; decimal code point -->
<!-- &#xHHH; hexadecimal code point -->CDATA のセクション
エスケープなしで <、>、& を含めさせてくれるのが、CDATA のセクションです — コードとマークアップに有用です。リテラルに「]]>」を含められないのが、CDATA です。それを埋め込むには、示されたようにセクションを分割しましょう。文字データであり、要素としてパースされないのが、CDATA です。
<?xml version="1.0"?>
<root>
<script><![CDATA[
function check(a, b) {
if (a < b && b > 0) {
return a & b;
}
}
]]></script>
<!-- to include ]]> inside CDATA, split it -->
<data><![CDATA[foo]]]]><![CDATA[>bar]]></data>
</root>カスタムエンティティ(DTD)
DTD で宣言され、参照されるところであればどこでも展開されるのが、内部エンティティです。テキストのマクロのように振る舞い、他のエンティティを参照できます。繰り返される定型文に有用です。注意:外部/一般のエンティティは、XXE のセキュリティリスクになり得ます。
<?xml version="1.0"?>
<!DOCTYPE root [
<!ENTITY company "Acme Corp.">
<!ENTITY version "2.0">
<!ENTITY copyright "Copyright © 2024 &company;">
]>
<root>
<product>&company; Toolkit v&version;</product>
<footer>©right;</footer>
</root>
<!-- Entities are expanded during parsing -->属性内でのエスケープ
属性の値の内側では、& を & としてエスケープし、値を区切る引用符の文字(" か ')をエスケープしなければなりません。< もエスケープされるべきです。属性内の改行とタブを、パーサーがスペースへ正規化します。
<?xml version="1.0"?>
<root>
<link url="https://example.com?a=1&b=2"/>
<msg text="Say "hello" & smile"/>
<path value='C:\Users\name'/>
<data value="<tagged>"/>
</root>パラメータエンティティ
再利用可能なコンテンツモデルを構築するため、DTD の内側でのみ使われるのが(% で宣言される)、パラメータエンティティです。%name;(セミコロン付き)として参照されます。文書のコンテンツで使われるのが、(&name; の)一般エンティティです。
<?xml version="1.0"?>
<!DOCTYPE root [
<!ENTITY % inline " (#PCDATA | em | strong)* ">
<!ELEMENT p %inline;>
<!ELEMENT em %inline;>
<!ELEMENT strong %inline;>
<!ELEMENT root (p)*>
]>
<root>
<p>Hello <em>world</em> and <strong>XML</strong>.</p>
</root>DTD(Document Type Definition)
内部 DTD
DOCTYPE 内の角括弧の中でインラインで宣言されるのが、内部 DTD です。構造を定義します:どの要素が存在するか、それらのコンテンツモデル、属性です。自己完結ですが、その 1 つの文書にのみ適用されるのが、内部 DTD です。
<?xml version="1.0"?>
<!DOCTYPE note [
<!ELEMENT note (to, from, heading, body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
<note>
<to>Alice</to>
<from>Bob</from>
<heading>Reminder</heading>
<body>Don't forget the meeting</body>
</note>外部 DTD
SYSTEM( プライベート)か PUBLIC(公開識別子 + URI)で参照される、別の .dtd ファイルに住むのが、外部 DTD です。多くの文書が 1 つの定義を共有できるのが、外部 DTD です。最もよくある形式が、SYSTEM 'file.dtd' です。
<!-- File: note.dtd -->
<!ELEMENT note (to, from, body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT body (#PCDATA)>
<!-- File: note.xml -->
<?xml version="1.0"?>
<!DOCTYPE note SYSTEM "note.dtd">
<note>
<to>Alice</to>
<from>Bob</from>
<body>Hello</body>
</note>要素の宣言
コンテンツモデルが使うもの:,(シーケンス)、|(選択)、?(0〜1)、*(0+)、+(1+)です。テキストであるのが、#PCDATA で、要素と混ざるテキストを許すのが、mixed content です。コンテンツなしを意味するのが、EMPTY で、チェックを無効化するのが(本番では避けましょう)、ANY です。
<!ELEMENT root (child1, child2*)>
<!-- content model operators -->
<!ELEMENT list (item+)> <!-- one or more item -->
<!ELEMENT opt (item?)> <!-- zero or one item -->
<!ELEMENT any (item1 | item2)*> <!-- choice, any number -->
<!ELEMENT text (#PCDATA)> <!-- parsed character data -->
<!ELEMENT mixed (#PCDATA | em)*> <!-- mixed content -->
<!ELEMENT empty EMPTY> <!-- no content -->
<!ELEMENT any ANY> <!-- any content -->属性の宣言
属性のタイプとデフォルトを宣言するのが、ATTLIST です。一意の識別子であるのが、ID で、ID を参照するのが(相互リンクのため)、IDREF/IDREFS です。名前のトークンであるのが、NMTOKEN です。許される値を列挙するのが、列挙型です。デフォルト:#REQUIRED、#IMPLIED、#FIXED、リテラルです。
<!ATTLIST book
id ID #REQUIRED
category CDATA #IMPLIED
lang NMTOKEN "en"
status (draft|final) "draft"
version CDATA #FIXED "1.0">
<!-- Types: CDATA, ID, IDREF, IDREFS, NMTOKEN, NMTOKENS,
NOTATION, enumerated (a|b|c) -->
<!ATTLIST link ref IDREF #REQUIRED>エンティティの宣言
コンテンツで展開されるのが、(&name; の)一般エンティティで、DTD で展開されるのが、(%name; の)パラメータエンティティです。他の XML を含むのが、外部の解析済みエンティティで、(NDATA 付きの)解析されていないエンティティが、NOTATION 経由で参照される非 XML のデータを指します。外部エンティティは、XXE インジェクションを引き起こし得ます。
<!DOCTYPE root [
<!-- internal general entity -->
<!ENTITY name "Alice">
<!-- external parsed entity -->
<!ENTITY chap1 SYSTEM "chapter1.xml">
<!-- unparsed entity (binary, e.g. image) -->
<!ENTITY logo SYSTEM "logo.png" NDATA image>
<!-- notation declaration for unparsed entities -->
<!NOTATION image SYSTEM "image/png">
<!-- parameter entity (DTD-only) -->
<!ENTITY % block "(p | list)+">
]>
<root>&name;</root>DTD の検証
文書がその DTD に一致するかチェックするのが、検証です(要素の順序、許される属性、ID の一意性)。デフォルトでは検証しないのが、minidom のような標準の DOM パーサーです — lxml(Python)、xmllint(コマンドライン)、検証するパーサーを使いましょう。
<?xml version="1.0"?>
<!DOCTYPE root SYSTEM "schema.dtd">
<root>
<item id="x1">valid</item>
</root>
<!-- Validate with Python: -->
<!-- import xml.dom.minidom as m
dom = m.parse("file.xml")
# minidom does NOT validate; use lxml: -->
<!-- from lxml import etree
dtd = etree.DTD("schema.dtd")
tree = etree.parse("file.xml")
print(dtd.validate(tree)) -->XML Schema(XSD)
スキーマの構造
XSD 自体が、XML の文書です。定義する要素のための、XSD の名前空間とターゲットの名前空間を宣言するのが、ルートの <schema> です。ローカルの要素をターゲットの名前空間へ置くのが、elementFormDefault='qualified' です。
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="https://example.com/order"
xmlns:tns="https://example.com/order"
elementFormDefault="qualified">
<xs:element name="order" type="tns:OrderType"/>
<xs:complexType name="OrderType">
<xs:sequence>
<xs:element name="customer" type="xs:string"/>
<xs:element name="total" type="xs:decimal"/>
</xs:sequence>
<xs:attribute name="id" type="xs:ID" use="required"/>
</xs:complexType>
</xs:schema>単純型
ファセット(pattern、minInclusive、enumeration、length など)で基本型を制限するのが、simpleType です。テキストのコンテンツと属性だけを持ち、子の要素を持たないのが、単純型です。スキーマをまたいで再利用可能です。
<xs:simpleType name="emailType">
<xs:restriction base="xs:string">
<xs:pattern value="[^@]+@[^@]+.[^@]+"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="ageType">
<xs:restriction base="xs:integer">
<xs:minInclusive value="0"/>
<xs:maxInclusive value="120"/>
</xs:restriction>
</xs:simpleType>
<xs:element name="email" type="tns:emailType"/>
<xs:element name="age" type="tns:ageType"/>複合型
子の要素と属性を保持できるのが、complexType です。順序を強制するのが、sequence で、いくつかのうちの 1 つを許すのが、choice、任意の順序を許すのが(それぞれ最大 1 回)、all です。豊富な構造を表現するため、コンポジタがネストできます。
<xs:complexType name="AddressType">
<xs:sequence>
<xs:element name="street" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="zip" type="xs:string"/>
</xs:sequence>
<xs:attribute name="country" type="xs:string" default="US"/>
</xs:complexType>
<!-- Content model indicators: sequence, choice, all -->
<xs:complexType name="ContactType">
<xs:choice>
<xs:element name="phone" type="xs:string"/>
<xs:element name="email" type="xs:string"/>
</xs:choice>
</xs:complexType>組み込みの型
豊富な型の階層を XSD が提供します:文字列、数値(integer、decimal、float)、日付/時間、boolean、anyURI、ID/IDREF、そして QName です。さらなる制限のための、length、pattern、enumeration のようなファセットを、それぞれがサポートします。
<!-- Common XSD built-in types -->
<xs:element name="count" type="xs:integer"/>
<xs:element name="price" type="xs:decimal"/>
<xs:element name="flag" type="xs:boolean"/>
<xs:element name="name" type="xs:string"/>
<xs:element name="date" type="xs:date"/> <!-- 2024-01-15 -->
<xs:element name="time" type="xs:time"/> <!-- 13:45:00 -->
<xs:element name="dt" type="xs:dateTime"/> <!-- 2024-01-15T13:45:00 -->
<xs:element name="id" type="xs:ID"/>
<xs:element name="ref" type="xs:IDREF"/>
<xs:element name="uri" type="xs:anyURI"/>制限(ファセット)
単純型を制約するのが、ファセットです:enumeration(許される値)、pattern(正規表現)、length/minLength/maxLength、min/maxInclusive/Exclusive、totalDigits、fractionDigits、そして whiteSpace(preserve/replace/collapse)です。
<xs:simpleType name="ColorType">
<xs:restriction base="xs:string">
<xs:enumeration value="red"/>
<xs:enumeration value="green"/>
<xs:enumeration value="blue"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="PasswordType">
<xs:restriction base="xs:string">
<xs:minLength value="8"/>
<xs:maxLength value="32"/>
<xs:pattern value="[A-Za-z0-9!@#]+"/>
</xs:restriction>
</xs:simpleType>XSD の要素と属性
基数を制御するのが、minOccurs/maxOccurs です(デフォルト 1)。任意の数を許すのが、maxOccurs='unbounded' です。required/optional/prohibited であるのが、属性の「use」で、オプションの default か fixed の値があります。定義をインライン化するのが、匿名の複合型です。
<xs:element name="product">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"
minOccurs="1" maxOccurs="1"/>
<xs:element name="tag" type="xs:string"
minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
<xs:attribute name="sku" type="xs:string" use="required"/>
<xs:attribute name="weight" type="xs:decimal" use="optional"
default="0.0"/>
</xs:complexType>
</xs:element>XPath
パス式
パス風の式を使うのが、XPath です。ルートから選択するのが、「/」で、任意の深さの子孫を選択するのが、「//」です。任意の要素のワイルドカードであるのが、「*」で、属性を選択するのが、「@」です。「/」で始まる式が、絶対です。
<!-- Sample: <bookstore><book><title>..</title></book></bookstore> -->
/bookstore/book/title <!-- absolute path -->
bookstore/book/title <!-- relative path -->
//title <!-- any title, anywhere -->
/bookstore//title <!-- title anywhere under bookstore -->
bookstore/* <!-- all children of bookstore -->
//@lang <!-- all lang attributes -->
//@* <!-- all attributes -->述語
ノードのセットをフィルタするのが、[ ] 内の述語です。1 ベースであるのが、インデックスです。そのコンテキストでのノードの位置を参照するのが、last() と position() です。要素のテキスト、属性(@name)、計算された値をテストできるのが、述語です。
//book[1] <!-- first book -->
//book[last()] <!-- last book -->
//book[position() <= 3] <!-- first three books -->
//book[price > 25] <!-- books with price > 25 -->
//book[@category='web'] <!-- books in the web category -->
//book[author='Smith'] <!-- books authored by Smith -->
//book[@lang][2] <!-- 2nd book that has a lang attr -->軸
ナビゲーションの方向を定義するのが、軸です:child(デフォルト)、descendant、parent(..)、ancestor、following-sibling、preceding-sibling、attribute(@)、self(.)、descendant-or-self(//)です。ほとんどが、実践で使われる省略形を持ちます。
child::book <!-- default axis: children named book -->
descendant::title <!-- all title descendants -->
parent::* <!-- the parent element (shorthand: ..) -->
ancestor::section <!-- all section ancestors -->
following-sibling::p <!-- p elements after this one -->
preceding::item <!-- items before this in document order -->
attribute::id <!-- the id attribute (shorthand: @id) -->
self::node() <!-- the current node (shorthand: .) -->関数
組み込みの関数があるのが、XPath 1.0 です:count、sum、string-length、contains、starts-with、normalize-space、name、concat、substring、round などです。関数ライブラリを大きく拡張し、型付けを加えるのが、XPath 2.0+ です。
count(//book) <!-- number of book elements -->
string-length(//title) <!-- length of first title's text -->
contains(//name, 'Ali') <!-- true if name contains 'Ali' -->
starts-with(@id, 'b') <!-- true if id starts with 'b' -->
normalize-space(//summary) <!-- collapse whitespace -->
name(//*[1]) <!-- name of the first element -->
concat(/a, /b) <!-- concatenate strings -->
sum(//price) <!-- sum of all price values -->演算子
等価性に = を使い(単一の = で、== ではありません)、ロジックに「and」「or」の演算子を使うのが(&& / || ではなく)、XPath です。「/」がパスのために予約されるため、除算が「div」で、剰余が「mod」です。ノードのセットの和集合を計算するのが、「|」です。
<!-- Comparison: =, !=, <, >, <=, >= -->
//book[price = 29.99]
//book[price < 20]
<!-- Logical: and, or -->
//book[price > 10 and price < 30]
//book[@cat='a' or @cat='b']
<!-- Arithmetic: + - * div mod -->
//item[price * quantity > 100]
5 div 2 <!-- 2.5 -->
5 mod 2 <!-- 1 -->
<!-- Union: | -->
//book | //magazineXPath の例
本物のクエリのため、これらのパターンが、パス、述語、関数を組み合わせます。テキストノードを選択するのが、text() で、XPath 2.0+ を必要とするのが、min() です。述語付きの //* のワイルドカードが、ツリー全体をまたいで属 性により要素を見つけるよくある方法です。
<!-- Select all book titles priced over 20 -->
//book[price > 20]/title/text()
<!-- The category of the cheapest book -->
//book[price = min(//book/price)]/@category
<!-- Authors of books in the 'programming' category -->
//book[@category='programming']/author
<!-- Every 2nd item in each list -->
//list/item[position() mod 2 = 0]
<!-- Elements with a specific attribute value -->
//*[@lang='fr']XSLT の変換
基本の変換
XML であるのが、XSLT のスタイルシートです。XPath でノードにマッチするのが、テンプレートで、選択されたノードを再帰的に処理するのが、apply-templates です。テキストを抽出するのが、value-of です。文書のルート上で最初に走るのが、match='/' のテンプレートです。
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>Book List</h2>
<xsl:apply-templates select="bookstore/book"/>
</body>
</html>
</xsl:template>
<xsl:template match="book">
<p><xsl:value-of select="title"/> - <xsl:value-of select="price"/></p>
</xsl:template>
</xsl:stylesheet>xsl:template と apply-templates
プロセッサがマッチするノードを訪れると発火するのが、match のテンプレートで、call-template で明示的に呼ばれるのが、名前付きのテンプレートです。select なしの apply-templates が、すべての子を処理し、再帰的でルール駆動の変換を可能にします。
<xsl:template match="book">
<div class="book">
<xsl:apply-templates select="title"/>
<xsl:apply-templates select="author"/>
</div>
</xsl:template>
<xsl:template match="title">
<h3><xsl:apply-templates/></h3>
</xsl:template>
<!-- named template (like a function) -->
<xsl:template name="divider">
<hr/>
</xsl:template>xsl:value-of と xsl:for-each
ノードのセットを反復し、コンテキストノードを変えるのが、xsl:for-each です。フラットな出力にはテンプレートよりしばしば単純ですが、使いすぎるとスタイルシートが手続き的になります。再帰的な構造には、テンプレートと apply-templates を優先しましょう。
<xsl:template match="/">
<ul>
<xsl:for-each select="bookstore/book">
<li>
<xsl:value-of select="title"/>
(<xsl:value-of select="@category"/>)
</li>
</xsl:for-each>
</ul>
</xsl:template>
<!-- value-of outputs the string value of an expression -->xsl:if と xsl:choose
else を持たないのが、xsl:if です — 多方向の分岐には、xsl:choose を使いましょう。XPath のブールの規則に従うのが、「test」の式です:空でないノードのセットが true で、空のものが false、非ゼロの数値が true です。
<xsl:for-each select="bookstore/book">
<xsl:if test="price > 25">
<premium><xsl:value-of select="title"/></premium>
</xsl:if>
<xsl:choose>
<xsl:when test="@category='fiction'">F</xsl:when>
<xsl:when test="@category='programming'">P</xsl:when>
<xsl:otherwise>?</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
<!-- test uses XPath; non-empty node-sets and non-zero numbers are true -->xsl:sort と xsl:variable
1 つ以上のキーで現在のノードのセットを並べ替えるのが、xsl:sort で、「text」か「number」であるのが、data-type です。不変でスコープされるのが、(xsl:variable の)変数です。スタイルシートの XML での属性値の内側で、< を < としてエスケープすることを覚えておきましょう。
<xsl:variable name="max-price" select="50"/>
<xsl:for-each select="bookstore/book[price < $max-price]">
<xsl:sort select="price" data-type="number" order="descending"/>
<xsl:sort select="title" order="ascending"/>
<p>
<xsl:value-of select="title"/>: <xsl:value-of select="price"/>
</p>
</xsl:for-each>
<!-- Note: in XSLT, < must be written < inside test attributes -->xsl:apply-templates と modes
1 セットのソースノードが 、異なる方法で(例:目次対完全なエントリ)処理されるのをさせてくれるのが、modes です。template と apply-templates の両方の mode 属性が、一致しなければなりません。モードなしでは、no-mode のテンプレートだけが適用されます。
<!-- A template can have a 'mode' for different outputs -->
<xsl:template match="book" mode="list">
<li><xsl:value-of select="title"/></li>
</xsl:template>
<xsl:template match="book" mode="detail">
<div><h3><xsl:value-of select="title"/></h3>
<p><xsl:value-of select="author"/></p></div>
</xsl:template>
<!-- Invoke a specific mode -->
<xsl:apply-templates select="bookstore/book" mode="list"/>
<xsl:apply-templates select="bookstore/book" mode="detail"/>XQuery
FLWOR 式
XQuery のコアの構成要素であるのが、FLWOR です:変数をシーケンスのアイテムにバインドするのが、for で、計算された値をバインドするのが、let、フィルタするのが、where、ソートするのが、order by、出力を形作るのが、return です。SQL の SELECT-FROM-WHERE に似ています。
for $b in /bookstore/book
let $discount := $b/price * 0.9
where $b/price > 20
order by $b/price descending
return
<book>
<title>{ $b/title/text() }</title>
<salePrice>{ $discount }</salePrice>
</book>
<!-- FLWOR = For, Let, Where, Order by, Return -->パス式
XPath を直接埋め込むのが、XQuery です。文書をロードするのが、doc('file.xml') で、複数の文書をクエリするのが、collection('uri') です。ノードのシーケンスを返すのが、パス式で、FLWOR 式がそれを反復できます。
(: XQuery uses XPath for navigation :)
/bookstore/book/title/text()
/bookstore/book[@category='web']
//author[contains(., 'Smith')]
(: Use doc() to open an external document :)
doc('catalog.xml')//book[price < 30]
(: collection() queries a set of documents :)
collection('/db/books')//title述語と結合
(SQL の JOIN のような)結合を形成するのが、複数の「for」句です。組み合わせを反復し where でフィルタすることで、結合を実行するのが、XQuery です。大きなデータセットのためには、ネストしたループより、述語かキー経由の明示的な結合がより効率的です。
(: Join books to authors by id :)
for $b in doc('books.xml')//book
for $a in doc('authors.xml')//author
where $b/@author-id = $a/@id
return
<entry>
<title>{ $b/title/text() }</title>
<author>{ $a/name/text() }</author>
</entry>
(: Equivalent join with a predicate :)
for $b in doc('books.xml')//book
return
<entry>{ $b/title, $b/@author-id }</entry>条件と 量化
if-then-else(else が必須)、量化された式(some/every ... satisfies)、ノードのタイプでの分岐のための typeswitch を持つのが、XQuery です。XPath 風のブールのセマンティクスを使うのが、条件です。
(: if-then-else :)
for $b in //book
return
if ($b/price > 30) then <expensive>{ $b/title }</expensive>
else <cheap>{ $b/title }</cheap>
(: quantified expressions :)
some $a in //author satisfies contains($a, 'Smith')
every $p in //price satisfies $p > 0
(: typeswitch for type-based dispatch :)
typeswitch($node)
case element(book) return "book"
case element(author) return "author"
default return "other"関数
XPath の関数を再利用し、多くを加えるのが(string-join、distinct-values、avg、min、max)、XQuery です。パラメータと戻り値の型付きで、local: の名前空間で慣例により、モジュールで宣言されるのが、ユーザーの関数です。
(: Built-in functions :)
concat('a', 'b', 'c')
string-join(//title, ', ')
count(//book)
distinct-values(//book/@category)
avg(//book/price)
max(//book/price)
(: User-defined function :)
declare function local:discount($price as xs:decimal)
as xs:decimal {
$price * 0.9
};
local:discount(29.99)XML の構築
直接のコンストラクタ({ } で埋め込み式を持つリテラルのタグ)か、計算されたコンストラクタ(element name { ... })で、XML を構築するのが、XQuery です。囲まれた式を評価するのが、波括弧で、値をインラインで埋め込めるのが、属性です。
(: Direct element construction :)
<result>
<count>{ count(//book) }</count>
<books>
{ for $b in //book return <book title="{ $b/title/text() }"/> }
</books>
</result>
(: Computed constructors :)
element result {
attribute total { count(//book) },
for $b in //book
return element book { $b/title/text() }
}
(: Enclosed expressions use { } to embed values -->DOM のパース
XML のロード(JavaScript)
ブラウザで XML の文字列を DOM ツリーへ変えるのが、DOMParser です。パースのエラーが、例外 でなく <parsererror> の要素として現れます。組み込みの XML DOM を持たないのが、Node.js です — xmldom、@xmldom/xmldom、ストリーミングのパーサーを使いましょう。
// Browser: parse an XML string
const parser = new DOMParser();
const doc = parser.parseFromString(xmlString, "application/xml");
const errorNode = doc.querySelector("parsererror");
if (errorNode) {
console.error("Parse error:", errorNode.textContent);
}
const books = doc.getElementsByTagName("book");
for (const book of books) {
console.log(book.getAttribute("id"));
}
// Node.js: use xmldom or fast-xml-parser insteadDOM の走査
走査のための documentElement、children、childNodes、nextSibling を DOM API が公開します。要素であるのが nodeType 1 で、テキストが 3、コメントが 8 です。ブラウザで XPath を走らせるのが、document.evaluate です(Node には xpath のライブラリが必要です)。
// JavaScript DOM API (also works for XML documents)
const root = doc.documentElement; // <bookstore>
const firstBook = root.children[0]; // first <book>
const titles = doc.getElementsByTagName("title");
// walk children
let node = root.firstChild;
while (node) {
if (node.nodeType === 1) { // Element node
console.log(node.tagName);
}
node = node.nextSibling;
}
// XPath against the DOM
const it = doc.evaluate("//book[@id='b1']", doc, null,
XPathResult.ANY_TYPE, null);
const found = it.iterateNext();DOM の修正
ノードを構築し付けるのが、createElement/setAttribute/appendChild で、テキストを設定するのが、textContent です。DOM を文字列へ戻すのが、XMLSerializer です。ライブであるのが DOM であり — ミューテーションが、任意の参照に即座に反映されます。
const book = doc.createElement("book");
book.setAttribute("id", "b3");
const title = doc.createElement("title");
title.textContent = "New Book";
book.appendChild(title);
root.appendChild(book); // add to tree
// change an existing element
const price = doc.querySelector("book:nth-child(2) price");
price.textContent = "19.99";
price.setAttribute("currency", "EUR");
// serialize back to a string
const xml = new XMLSerializer().serializeToString(doc);要素の作成
ゼロから文書を構築させてくれるのが、minidom です:ルートには createDocument、コンテンツには createElement/setAttribute/createTextNode、リンクには appendChild です。インデント付きで serial 化するのが、toprettyxml です。単純ですが、大きなツリーでは遅いのが、minidom です。
// Python: xml.dom.minidom
from xml.dom import minidom
impl = minidom.getDOMImplementation()
doc = impl.createDocument(None, "root", None)
root = doc.documentElement
item = doc.createElement("item")
item.setAttribute("id", "1")
item.appendChild(doc.createTextNode("Hello"))
root.appendChild(item)
print(doc.toprettyxml(encoding="UTF-8").decode())Java の DOM パース
DocumentBuilder 経由で文書全体をメモリへロードするのが、Java の JAXP DOM です。名前空間の接頭辞を保つのが、setNamespaceAware(true) です。ランダムアクセスに便利ですが、大きなファイルでメモリ重いのが、DOM です — その場合は、StAX/SAX を優先しましょう。
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.*;
DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
f.setNamespaceAware(true);
Document doc = f.newDocumentBuilder().parse(new File("data.xml"));
Element root = doc.getDocumentElement();
NodeList books = root.getElementsByTagName("book");
for (int i = 0; i < books.getLength(); i++) {
Element b = (Element) books.item(i);
String id = b.getAttribute("id");
String title = b.getElementsByTagName("title")
.item(0).getTextContent();
System.out.println(id + ": " + title);
}lxml(Python)
libxml2 の速く機能豊富な Python のバインディングであるのが、lxml です。完全な XPath、XSLT、検証(DTD/XSD/RelaxNG)、インクリメンタルなパースをサポートします。XPath のサブセットであるのが、その ElementPath(find/findall)で、完全な XPath には、xpath() を使いましょう。
from lxml import etree
# parse and validate against a schema
tree = etree.parse("data.xml")
root = tree.getroot()
# XPath with namespaces
ns = {"bk": "https://example.com/books"}
for book in root.xpath("//bk:book", namespaces=ns):
print(book.get("id"), book.find("bk:title", namespaces=ns).text)
# build an element tree
root = etree.Element("root")
child = etree.SubElement(root, "item", id="1")
child.text = "Hello"
print(etree.tostring(root, pretty_print=True, encoding="unicode"))SAX のパース
SAX のハンドラ(Python)
イベント駆動でストリーミングであるのが、SAX です:読むにつれ、パーサーが startElement、characters、endElement を呼び、完全なツリーを決して構築しません。巨大なファイルでメモリ効率が良いです。状態(例:現在の要素)を自分で追跡しなければなりません。
import xml.sax
class BookHandler(xml.sax.ContentHandler):
def startElement(self, name, attrs):
if name == "book":
print("Book id:", attrs.getValue("id"))
self.current = name
def characters(self, content):
if self.current == "title":
print("Title:", content.strip())
def endElement(self, name):
self.current = None
xml.sax.parse("books.xml", BookHandler())SAX のイベントメソッド
文書と要素の境界を印付けるのが、ContentHandler のコールバックです。単一のテキストノードを複数の呼び出しに分割し得るのが、characters() です — バッファへ蓄積しましょう。名前空間の宣言を報告するのが、startPrefixMapping/endPrefixMapping です。
class Handler(xml.sax.ContentHandler):
def startDocument(self):
print("parsing started")
def endDocument(self):
print("parsing done")
def startElement(self, name, attrs):
# attrs: get via attrs.getValue('id') or attrs['id']
pass
def endElement(self, name):
pass
def characters(self, text):
# may be called multiple times for one text node
pass
def startPrefixMapping(self, prefix, uri):
print("namespace:", prefix, uri)startElement / endElement
ストリーミングの間、位置を知る標準の方法であるのが、(スタックである)要素のパスの追跡です。characters() の出力をバッファし、endElement でフラッシュしましょう。テキストノードごとに複数回発火し得るのが、characters だからです。
class Handler(xml.sax.ContentHandler):
def __init__(self):
self.path = []
self.text = []
def startElement(self, name, attrs):
self.path.append(name)
self.text = []
if "id" in attrs:
print("/".join(self.path), "id =", attrs["id"])
def endElement(self, name):
if self.path[-1] == "title":
print("title:", "".join(self.text).strip())
self.path.pop()
def characters(self, content):
self.text.append(content)Java の SAX パーサー
DefaultHandler を拡張するのが、Java の SAX です。名前空間の URI、ローカル名、修飾名、Attributes のオブジェクトを受け取るのが、startElement です。char のスライスを提供するのが、characters(ch, start, len) で — テキストノードが複数の呼び出しにまたがり得るため、バッファしましょう。
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.*;
import javax.xml.parsers.*;
class BookHandler extends DefaultHandler {
private StringBuilder buf = new StringBuilder();
public void startElement(String uri, String local,
String qName, Attributes attrs) {
buf.setLength(0);
if ("book".equals(qName))
System.out.println("id=" + attrs.getValue("id"));
}
public void characters(char[] ch, int start, int len) {
buf.append(ch, start, len);
}
public void endElement(String uri, String local, String qName) {
if ("title".equals(qName))
System.out.println("title=" + buf);
}
}
// SAXParserFactory.newInstance().newSAXParser().parse(file, new BookHandler());SAX 対 DOM
一定のメモリでイベントをストリームするのが、SAX で、巨大なファイルと 1 パスの抽出に理想的です。ツリー全体をロードするのが、DOM で、XPath とランダムなミューテーションを可能にしますが、ファイルサイズに比例したメモリを使います。アクセスのパターンとファイルサイズに基づき選びましょう。
<!-- SAX: event-driven, streaming, low memory
DOM: full tree in memory, random access
SAX is best for:
- large files that won't fit in memory
- read-only filtering / extraction
- simple state machines over the document
DOM is best for:
- random access to many parts of the tree
- repeated queries / XPath
- editing and re-serializing -->
<!-- Memory: SAX ~ O(1); DOM ~ O(file size) -->
<!-- Speed: SAX often faster for one-pass scans -->エラー処理(SAX)
警告、回復可能なエラー、致命的なエラーを受け取るのが、ErrorHandler です。デフォルトで、致命的なエラーが例外を上げ、パースを止めます。error() を実装すると、パース全体を中止せずに、非致命的な検証の問題をログできます。
import xml.sax
class Handler(xml.sax.ContentHandler):
pass
# ErrorHandler: warning, error, fatalError
class ErrHandler(xml.sax.ErrorHandler):
def error(self, exception):
print("ERROR:", exception)
def fatalError(self, exception):
print("FATAL:", exception)
raise exception
def warning(self, exception):
print("WARN:", exception)
parser = xml.sax.make_parser()
parser.setContentHandler(Handler())
parser.setErrorHandler(ErrHandler())
parser.parse("data.xml")StAX(プルパース)
StAX の Cursor API
プルパーサーであるのが、StAX です:next() で次のイベントを引き出すのが、あなたのコードであり、ループを制御します。一度に 1 つのイベントを進むのが、(XMLStreamReader の)cursor API です。DOM より速くメモリが少なく、SAX のプッシュモデルより柔軟です。
import javax.xml.stream.*;
import java.io.*;
XMLInputFactory factory = XMLInputFactory.newInstance();
// defend against XXE
factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
factory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
XMLStreamReader r = factory.createXMLStreamReader(new FileInputStream("data.xml"));
while (r.hasNext()) {
int event = r.next();
if (event == XMLStreamConstants.START_ELEMENT) {
System.out.println("start: " + r.getLocalName());
} else if (event == XMLStreamConstants.END_ELEMENT) {
System.out.println("end: " + r.getLocalName());
}
}
r.close();XMLStreamReader のイベント
イベントのタイプには、START_ELEMENT、END_ELEMENT、CHARACTERS、COMMENT、PROCESSING_INSTRUCTION、START/END_DOCUMENT が含まれます。現在のテキストを返すのが、getText() で、インデントをフィルタするのが、isWhiteSpace() です。next() の呼び出しごとに 1 つのイベントが進むのが、cursor です。
XMLStreamReader r = factory.createXMLStreamReader(in);
while (r.hasNext()) {
switch (r.next()) {
case XMLStreamConstants.START_ELEMENT:
// r.getLocalName(), r.getAttributeValue(i), r.getNamespaceURI()
break;
case XMLStreamConstants.END_ELEMENT:
break;
case XMLStreamConstants.CHARACTERS:
if (!r.isWhiteSpace()) {
String text = r.getText();
}
break;
case XMLStreamConstants.START_DOCUMENT:
break;
case XMLStreamConstants.END_DOCUMENT:
break;
case XMLStreamConstants.PROCESSING_INSTRUCTION:
break;
}
}要素と属性の読み取り
名前により属性を読むのが、getAttributeValue(namespaceURI, localName) です(名前空間なしには null を渡します)。テキストのみの要素のテキストを読み、その END_ELEMENT を越えて進む便利なものが、getElementText() で — 自分で characters をバッファするよりきれ いです。
while (r.hasNext()) {
int event = r.next();
if (event == XMLStreamConstants.START_ELEMENT
&& "book".equals(r.getLocalName())) {
String id = r.getAttributeValue(null, "id");
String category = r.getAttributeValue(null, "category");
System.out.println("Book " + id + " (" + category + ")");
}
if (event == XMLStreamConstants.START_ELEMENT
&& "title".equals(r.getLocalName())) {
String title = r.getElementText(); // consumes until END_ELEMENT
System.out.println("Title: " + title);
}
}StAX のライター
順次に XML を構築するのが、XMLStreamWriter です。writeStartDocument、writeStartElement/writeEndElement、writeAttribute、writeCharacters、writeNamespace が、バランスされなければなりません。出力が完全であることを確保するため、最後に flush/close しましょう。
XMLOutputFactory out = XMLOutputFactory.newInstance();
XMLStreamWriter w = out.createXMLStreamWriter(System.out, "UTF-8");
w.writeStartDocument("UTF-8", "1.0");
w.writeStartElement("books");
w.writeNamespace("bk", "https://example.com/books");
w.writeStartElement("bk", "book", "https://example.com/books");
w.writeAttribute("id", "b1");
w.writeStartElement("bk", "title", "https://example.com/books");
w.writeCharacters("XML Guide");
w.writeEndElement(); // title
w.writeEndElement(); // book
w.writeEndElement(); // books
w.writeEndDocument();
w.close();StAX 対 SAX
イベントをハンドラへ押し込むのが、SAX で、オンデマンドでイベントを引き出せるのが、StAX です。サブツリーのスキップと状態の管理を容易にし、ライターの API を加えるのが、StAX のプルモデルです。どちらも、完全な DOM ツリーの構築を避けるため、大きな文書に適しています。
<!-- StAX: PULL model (client calls next())
SAX: PUSH model (parser calls your handlers)
StAX advantages:
- client controls parsing (easy to skip sections)
- simpler state management for many tasks
- supports both reading and writing
- can pause/resume naturally
SAX advantages:
- slightly lower overhead in pure streaming
- mature, widely available
- filters/chains via XMLFilter
Both are streaming and memory-efficient. -->Event Reader(Iterator API)
覗き見て消費できる XMLEvent オブジェクトを返すのが、(XMLEventReader の)iterator API です。cursor API よりオブジェクト指向で、フィルタや分割がより容易ですが、イベントオブジェクトの割り当てにより、わずかに重いです。
import javax.xml.stream.*;
import javax.xml.stream.events.*;
XMLEventReader reader = XMLInputFactory.newInstance()
.createXMLEventReader(in);
while (reader.hasNext()) {
XMLEvent e = reader.peek(); // look without consuming
if (e.isStartElement()) {
StartElement se = e.asStartElement();
System.out.println(se.getName());
}
XMLEvent consumed = reader.nextEvent(); // consume it
if (consumed.isEndElement()) {
System.out.println("closed");
}
}
reader.close();XML と JSON の変換
XML から JSON へ(JavaScript)
Node.js で XML を JSON へ変換す るのが、fast-xml-parser です。属性が接頭辞を付けられ(デフォルト @_)、繰り返される要素が配列になります。純粋な JavaScript で速いのがこのライブラリであり、配列、数値、ブールを制御するオプションがあります。
// Node.js with fast-xml-parser
const { XMLParser } = require("fast-xml-parser");
const xml = "<book id='b1'><title>XML</title><price>29.99</price></book>";
const parser = new XMLParser({
ignoreAttributes: false,
attributeNamePrefix: "@_",
});
const json = parser.parse(xml);
console.log(json.book["@_id"]); // b1
console.log(json.book.title); // XML
console.log(json.book.price); // 29.99JSON から XML へ(JavaScript)
変換を逆にするのが、XMLBuilder です。属性を印付けるのが、@_ の接頭辞で、ネストしたオブジェクトが子の要素になります。繰り返される要素を作るのが、配列です。XML の単一ルートの規則により、トップレベルの JSON オブジェクトが 1 つのルート要素へマッピングされなければなりません。
const { XMLBuilder } = require("fast-xml-parser");
const json = {
book: {
"@_id": "b1",
title: "XML Guide",
price: 29.99,
},
};
const builder = new XMLBuilder({
format: true,
attributeNamePrefix: "@_",
ignoreAttributes: false,
});
const xml = builder.build(json);
console.log(xml);
// <book id="b1">
// <title>XML Guide</title>
// <price>29.99</price>
// </book>Python の xmltodict
dict/list の構造のように XML を扱うのが、xmltodict です:属性が「@name」を使い、テキストが「#text」を使います。XML を読むのが、parse() で、書くのが、unparse() です。素早い往復に最適ですが、順序と、複雑なスキーマのいくつかのエッジケースが失われます。
import xmltodict, json
xml = """<book id="b1"><title>XML</title><price>29.99</price></book>"""
# XML -> dict
data = xmltodict.parse(xml)
print(data["book"]["@id"]) # b1
print(data["book"]["title"]) # XML
# dict -> JSON
print(json.dumps(data, indent=2))
# dict -> XML
xml_out = xmltodict.unparse({"book": {"@id": "b2", "title": "New"}})
print(xml_out)属性とテキストの処理
XML から JSON への変換は、属 性(@_ の接頭辞)、テキスト(#text)、mixed content についての決定を強制します。子の要素と混ざるテキストである、mixed content が、JSON へきれいにマッピングせず、しばしば忠実性が失われます。規約を選び、一貫して保ちましょう。
<!-- XML with mixed attributes and text -->
<product sku="A1" stock="5">Widget<note>sale</note></product>
// fast-xml-parser output:
// {
// product: {
// "@_sku": "A1",
// "@_stock": "5",
// "#text": "Widget",
// note: "sale"
// }
// }
// Round-trip carefully: mixed content (text + elements)
// is hard to represent losslessly in JSON -->変換の課題
よくある変換の落とし穴:単一対複数の子(配列対文字列)、要素の順序、(エイリアスである)名前空間の接頭辞、単一ルートの制約、プリミティブの型付け(XML にはネイティブの数値やブールがありません)です。規約を文書化しましょう。
<!-- 1. Repeated elements -> array -->
<list><item>a</item><item>b</item></list>
// { list: { item: ["a", "b"] } } (or single string if only one)
<!-- 2. Order is significant in XML but not in JSON objects -->
<a><x/><y/></a> vs <a><y/><x/></a> // may differ
<!-- 3. Namespaces -->
<ns:elem xmlns:ns="http://x"/> // prefixes are aliases
<!-- 4. Single root: JSON top-level must be one object -->
<!-- 5. Numbers/booleans: XML is all text; typing is heuristic -->往復の例
(XML -> JSON -> XML の)往復は、well 構造化されたデータには機能しますが、コメント、処理命令、CDATA の境界、正確な空白が落ち得ます。損失のない編集のためには、JSON の変換でなく、DOM/ツリーの API を使いましょう。
// Parse, modify, and re-serialize with fast-xml-parser
const { XMLParser, XMLBuilder } = require("fast-xml-parser");
const opts = { ignoreAttributes: false, attributeNamePrefix: "@_" };
const parser = new XMLParser(opts);
const builder = new XMLBuilder({ ...opts, format: true });
const obj = parser.parse(xmlString);
// mutate
obj.book.price = 19.99;
obj.book["@_onSale"] = "true";
const newXml = builder.build(obj);
console.log(newXml);RSS と Atom フィード
RSS 2.0 の構造
1 つの <channel> を持つ <rss> のルートがあるのが、RSS 2.0 です。必須の channel のフィールド:title、link、description です。各 <item> が、title、link、description、guid、pubDate を持ちます。RFC 822 に従うのが、日付です(例:「Wed, 02 Oct 2024 13:00:00 GMT」)。
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<title>My Blog</title>
<link>https://example.com</link>
<description>Recent posts</description>
<language>en-us</language>
<pubDate>Wed, 02 Oct 2024 13:00:00 GMT</pubDate>
<item>
<title>First Post</title>
<link>https://example.com/1</link>
<description>A short summary</description>
<pubDate>Wed, 02 Oct 2024 12:00:00 GMT</pubDate>
<guid>https://example.com/1</guid>
</item>
</channel>
</rss>RSS の Channel と Item
フィードを記述するのが、channel レベルのフィールドです(title、link、description、language、ttl、image)。各エントリを記述するのが、item のフィールドで、URL、バイト長、MIME タイプ付きの podcast/メディアをサポートするのが、enclosure です。domain 属性を運べるのが、category です。
<channel>
<title>Site Title</title>
<link>https://example.com</link>
<description>What the feed is about</description>
<category>Technology</category>
<ttl>60</ttl> <!-- cache minutes -->
<image>
<url>https://example.com/logo.png</url>
<title>Site Title</title>
<link>https://example.com</link>
</image>
<item>
<title>Post Title</title>
<link>https://example.com/post</link>
<description>Summary text</description>
<author>[email protected]</author>
<category domain="https://example.com/tags">xml</category>
<enclosure url="https://example.com/p.mp3" length="12345"
type="audio/mpeg"/>
</item>
</channel>Atom フィード
Atom の名前空間の <feed> ルートを使うのが、Atom(RFC 4287)です。必須:id、title、updated です。id、title、updated が必要なのが、entries です。グローバルに一意であるべきなのが(URN か tag: URI)、ID です。タイムゾーン付きの RFC 3339(ISO 8601)を使うのが、日付です。
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>Example Feed</title>
<link href="https://example.com/feed.atom" rel="self"/>
<link href="https://example.com"/>
<id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
<updated>2024-10-02T13:00:00Z</updated>
<author><name>Jane Doe</name></author>
<entry>
<title>Atom Entry</title>
<id>tag:example.com,2024:/post/1</id>
<updated>2024-10-02T12:00:00Z</updated>
<summary>A short summary</summary>
<content type="html"><p>Full post body</p></content>
</entry>
</feed>Atom の Entry の詳細
豊富なコンテンツを、Atom の entries がサポートします:type 属性経由の、text、html、xhtml です。rel の属性(alternate、self、enclosure、related)を使うのが、link です。term/scheme/label を持つのが、category です。元のの日付であるのが、published で、最後の変更が、updated です。
<entry>
<title type="text">Post Title</title>
<id>tag:example.com,2024:/posts/42</id>
<updated>2024-10-02T12:00:00Z</updated>
<published>2024-10-01T09:00:00Z</published>
<author>
<name>Jane Doe</name>
<email>[email protected]</email>
<uri>https://example.com/jane</uri>
</author>
<link href="https://example.com/posts/42" rel="alternate"/>
<category term="xml" scheme="https://example.com/tags" label="XML"/>
<summary type="text">A teaser.</summary>
<content type="xhtml">
<div xmlns="http://www.w3.org/1999/xhtml"><p>Body</p></div>
</content>
</entry>よくあるフィードの名前空間
モジュールでしばしば拡張されるのが、RSS です:Dublin Core(dc:creator、dc:date)、content(完全な HTML のための content:encoded)、Media RSS(media:content)、そしてリーダーがフィードの URL を見つける助けになる、atom:link rel='self' です。フィードが語彙を混ぜられるのが、名前空間です。
<?xml version="1.0"?>
<rss version="2.0"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:media="http://search.yahoo.com/mrss/"
xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>Feed</title>
<link>https://example.com</link>
<description>desc</description>
<atom:link href="https://example.com/feed.xml" rel="self"
type="application/rss+xml"/>
<item>
<title>Post</title>
<dc:creator>Jane Doe</dc:creator>
<content:encoded><![CDATA[<p>HTML body</p>]]></content:encoded>
<media:content url="https://example.com/img.png" medium="image"/>
</item>
</channel>
</rss>フィードの検証
RSS/Atom をチェックするには、W3C Feed Validator を使いましょう。よくあるエラー:必須フィールドの欠落、悪い日付の形式、非一意の ID、無効な XML(エスケープされない &)、self リンクの欠落です。有効なフィードが、アグリゲータが信頼性を持ってパースすることを確保します。
<!-- RSS: dates must be RFC 822, e.g. -->
<pubDate>Wed, 02 Oct 2024 13:00:00 GMT</pubDate>
<!-- Atom: dates must be RFC 3339, e.g. -->
<updated>2024-10-02T13:00:00Z</updated>
<!-- Validate online with https://validator.w3.org/feed/ -->
<!-- Required RSS channel fields: title, link, description -->
<!-- Required Atom feed fields: id, title, updated -->
<!-- GUIDs/IDs should be unique and permanent -->SVG と XML
SVG 文書の構造
ベクターグラフィックスのための XML の語彙であるのが、SVG です。SVG の名前空間と座標系のための viewBox を宣言するのが、ルートの <svg> です。プレゼンテーションの属性を持つ XML の要素であるのが、すべてのグラフィックの要素(rect、circle、text)です。
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="200" height="200" viewBox="0 0 200 200">
<rect x="10" y="10" width="180" height="180"
fill="#005FAD" stroke="black" stroke-width="2"/>
<circle cx="100" cy="100" r="40" fill="white"/>
<text x="100" y="105" text-anchor="middle">SVG</text>
</svg>
<!-- SVG is an XML application; it must be well-formed -->SVG の名前空間とインポート
http://www.w3.org/2000/svg の名前空間に住むのが、SVG の要素です。href の参照に使われるのが(SVG 1.1 で)、xlink で、素の href を優先するのが、SVG 2 です。url(#id) 経由で id により参照される、再利用可能なグラデーション、パターン、シンボルを保持するのが、defs です。
<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
version="1.1">
<defs>
<linearGradient id="g1">
<stop offset="0%" stop-color="red"/>
<stop offset="100%" stop-color="blue"/>
</linearGradient>
</defs>
<rect width="100" height="100" fill="url(#g1)"/>
</svg>SVG の形状
SVG の形状の要素:rect(丸い角のための rx/ry 付き)、circle、ellipse、line、polyline(開いた)、そして polygon(閉じた)です。viewBox により定義されたユーザー単位にあるのが、座標です。よくあるプレゼンテーションの属性であるのが、stroke と fill です。
<svg xmlns="http://www.w3.org/2000/svg" width="300" height="200">
<rect x="10" y="10" width="80" height="50" rx="10" fill="teal"/>
<circle cx="150" cy="60" r="40" fill="orange"/>
<ellipse cx="220" cy="60" rx="50" ry="20" fill="purple"/>
<line x1="10" y1="120" x2="290" y2="120" stroke="black"/>
<polyline points="10,180 50,140 90,180 130,140" fill="none" stroke="red"/>
<polygon points="200,180 250,140 280,200" fill="green"/>
</svg>SVG のテキストとパス
font-family、font-size、font-weight、font-style を使うのが、SVG のテキストです。text 要素の内側で混ぜたスタイリングを可能にするのが、tspan です。コマンドを使うのが、path 要素の「d」属性です:M(move)、L(line)、C(三次ベジェ)、Q(二次)、A(弧)、Z(パスを閉じる)です。
<svg xmlns="http://www.w3.org/2000/svg" width="300" height="150">
<text x="10" y="40" font-family="Arial" font-size="24"
font-weight="bold" fill="navy">Hello SVG</text>
<text x="10" y="80">
<tspan font-size="16">Normal</tspan>
<tspan font-size="16" font-style="italic"> italic</tspan>
</text>
<path d="M10 100 L 100 100 L 55 140 Z"
fill="none" stroke="black" stroke-width="2"/>
</svg>
<!-- Path commands: M=move, L=line, H/V, C=cubic, Q=quad, A=arc, Z=close -->SVG のグループ化と再利用
共有のスタイリングと transform のために形状をグループ化するのが、<g> 要素です。id により要素を参照し(SVG 2 では href='#id'、1.1 では xlink:href)、新しい位置でクローンを作るのが、<use> です。<use> 経由でのみ表示される、再利用可能なグラフィックスを定義するのが、<symbol> です。
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">
<g id="node" stroke="black" fill="lightblue">
<circle cx="50" cy="50" r="20"/>
<circle cx="100" cy="50" r="20"/>
</g>
<use href="#node" x="0" y="100"/>
<use href="#node" x="0" y="150" opacity="0.5"/>
<symbol id="star" viewBox="0 0 24 24">
<polygon points="12,2 15,9 22,9 17,14 19,21 12,17 5,21 7,14 2,9 9,9"/>
</symbol>
<use href="#star" width="24" height="24"/>
</svg>SVG の検証
W3C の DTD か XSD に対して、SVG の文書が検証できます。よくある問題:SVG の名前空間の忘れ、宣言されていない接頭辞、間違った名前空間の属性、形式の悪いパスのデータです。標準のコマンドラインの検証器であるのが、xmllint です。
<?xml version="1.0"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<rect width="100" height="100"/>
</svg>
<!-- Validate with xmllint: -->
<!-- xmllint --noout --valid file.svg (DTD) -->
<!-- xmllint --noout --schema svg11.xsd file.svg (XSD) -->
<!-- Common errors: wrong namespace, undeclared prefixes,
text outside a text element, invalid path data -->SOAP と WSDL
SOAP の Envelope
SOAP の名前空間の <Envelope> ルートを持つ XML の文書であるのが、SOAP メッセージです。メタデータ(auth、ルーティング)を運ぶのが、オプションの <Header> で、実際のメッセージのペイロードを保持するのが、必須の <Body> です。異なる名前空間を使うのが、SOAP 1.1 と 1.2 です。
<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<auth xmlns="https://example.com/auth">
<token>abc123</token>
</auth>
</soap:Header>
<soap:Body>
<m:GetPrice xmlns:m="https://example.com/pricing">
<m:Item>Apples</m:Item>
</m:GetPrice>
</soap:Body>
</soap:Envelope>
<!-- Envelope is the root; Header is optional, Body is required -->SOAP の Header
認証、アドレッシング(WS-Addressing)、トランザクションのような、帯域外の情報を運ぶのが、headers です。受信者がこのヘッダーを処理しなければ、SOAP fault を返さなければならないと伝えるのが、soap:mustUnderstand='1' で — これが、契約の遵守を強制します。
<soap:Header xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<wsa:Action xmlns:wsa="http://www.w3.org/2005/08/addressing">
http://example.com/GetPrice
</wsa:Action>
<wsa:MessageID>urn:uuid:1234</wsa:MessageID>
<auth xmlns="https://example.com/auth"
soap:mustUnderstand="1">
<token>secret</token>
</auth>
</soap:Header>
<!-- mustUnderstand="1" forces the receiver to process the header -->SOAP の Body と Fault
リクエストかレスポンスのペイロードを運ぶのが、Body です。エラー時、Body が、faultcode(Client/Server)、人間が読める faultstring、オプションの detail を持つ <Fault> を含みます。これらの要素を改名し、Code/Reason の構造を加えるのが、SOAP 1.2 です。
<!-- Request body -->
<soap:Body>
<m:GetPrice xmlns:m="https://example.com/pricing">
<m:Item>Apples</m:Item>
</m:GetPrice>
</soap:Body>
<!-- Fault (error response) -->
<soap:Body>
<soap:Fault>
<faultcode>soap:Client</faultcode>
<faultstring>Unknown item: Apples</faultstring>
<detail>
<m:Error xmlns:m="https://example.com/pricing">
<code>404</code>
</m:Error>
</detail>
</soap:Fault>
</soap:Body>WSDL の構造
Web サービスを記述するのが、WSDL です:<types>(XSD のスキーマ)、<message>(入力/出力のペイロード)、<portType>(インターフェイス — 操作とそのメッセージ)、<binding>(プロトコル/エンコーディング)、そして <service>(エンドポイントの URL)です。インターフェイスとバインディングへ簡素化するのが、WSDL 2.0 です。
<?xml version="1.0"?>
<definitions xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="https://example.com/pricing">
<types>
<xs:schema targetNamespace="https://example.com/pricing">
<xs:element name="GetPriceRequest" type="xs:string"/>
<xs:element name="GetPriceResponse" type="xs:decimal"/>
</xs:schema>
</types>
<message name="GetPriceInput">
<part name="item" element="tns:GetPriceRequest"/>
</message>
<portType name="PricingPort">
<operation name="GetPrice">
<input message="tns:GetPriceInput"/>
<output message="tns:GetPriceOutput"/>
</operation>
</portType>
</definitions>WSDL の Binding と Service
portType を具体的なプロトコル(HTTP 上の SOAP)とスタイルへマッピングするのが、binding で(モダンなデフォルトが document/literal です)、エンドポイント(soap:address)をリストするのが、service の要素です。schema 定義の要素でペイロードを包むのが、document/literal です。
<binding name="PricingSOAP" type="tns:PricingPort">
<soap:binding style="document"
transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="GetPrice">
<soap:operation soapAction="http://example.com/GetPrice"/>
<input><soap:body use="literal"/></input>
<output><soap:body use="literal"/></output>
</operation>
</binding>
<service name="PricingService">
<port name="PricingPort" binding="tns:PricingSOAP">
<soap:address location="https://example.com/pricing"/>
</port>
</service>
<!-- style: rpc or document; use: encoded or literal -->SOAP 対 REST
厳密な XML の envelope、WSDL の契約、WS-* の標準(セキュリティ、トランザクション)を持つプロトコルであるのが、SOAP で、信頼性と形式の契約を必要とする企業統合に最適です。軽量で HTTP ベースのスタイルであるのが、通常 JSON と共にある、REST で、公開 API を支配します。
<!-- SOAP: protocol with envelope, strict contract (WSDL),
built-in error model (Fault), WS-* extensions.
Heavier, XML-only, common in enterprise/B2B. -->
<!-- REST: architectural style using HTTP verbs (GET/POST/...),
flexible payloads (often JSON), no built-in contract.
Lighter, browser-friendly, dominant on the web. -->
<!-- When to use SOAP:
- you need strict contracts and tooling
- transactional reliability (WS-ReliableMessaging)
- standardized security (WS-Security)
- existing SOAP-based infrastructure -->
<!-- When to use REST:
- public APIs, mobile/web clients
- JSON payloads, HTTP caching
- simpler, faster iteration -->XML のデジタル署名
署名の構造
<SignedInfo>(何がどう署名されるか)、<SignatureValue>(canonical 化された SignedInfo 上の暗号の署名)、オプションの <KeyInfo>、参照されたデータを保持する <Object> を含むのが、XML 署名のルートの <Signature> です。
<?xml version="1.0"?>
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="..."/>
<SignatureMethod Algorithm="..."/>
<Reference URI="#data">
<DigestMethod Algorithm="..."/>
<DigestValue>...</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>...</SignatureValue>
<KeyInfo>...</KeyInfo>
<Object Id="data">signed content</Object>
</Signature>
<!-- A signature = SignedInfo + SignatureValue + optional KeyInfo -->SignedInfo
canonical 化(バイト同一の署名が XML の再 serial 化を生き延びるように)、署名のアルゴリズム、1 つ以上の References を指定するのが、SignedInfo です。各 Reference が、URI でデータを指し、Transforms をリストし、そのデータの DigestValue を与えます。
<SignedInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<CanonicalizationMethod
Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
<SignatureMethod
Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<Reference URI="">
<Transforms>
<Transform Algorithm="...enveloped-signature"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue>base64digest==</DigestValue>
</Reference>
</SignedInfo>Reference と Transforms
何を署名するか特定し(URI)、Transforms を適用し(canonical 化、XPath のフィルタリング、enveloped-signature の除去)、その後 DigestMethod でハッシュするのが、各 Reference です。Signature 要素自体を自身のハッシュから除外するのが、enveloped-signature の transform です。
<Reference URI="#order">
<Transforms>
<Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
<XPath xmlns="...">not(ancestor-or-self::ds:Signature)</XPath>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
<DigestValue>abc123base64==</DigestValue>
</Reference>
<!-- Reference types:
- same-document (URI="#id")
- external (URI="https://...")
- detached (URI pointing elsewhere) -->SignatureValue と KeyInfo
署名者の秘密鍵で canonical 化された SignedInfo を署名した、base64 の結果であるのが、SignatureValue です。OPTIONAL であり、検証の鍵をどう見つけるかだけをヒントするのが(X.509 証明書、RSA の公開鍵、鍵の名前、取得の URL)、KeyInfo で — 帯域外で検証されなければなりません。
<SignatureValue>base64encodedSignature==</SignatureValue>
<KeyInfo>
<X509Data>
<X509SubjectName>CN=Example,O=Example Inc</X509SubjectName>
<X509Certificate>MIID...base64...==</X509Certificate>
</X509Data>
</KeyInfo>
<!-- Other KeyInfo options: -->
<!-- <KeyName>key-id</KeyName> -->
<!-- <KeyValue><RSAKeyValue>...</RSAKeyValue></KeyValue> -->
<!-- <RetrievalMethod URI="..."/> -->
<!-- KeyInfo is optional and unverified by itself -->Canonical 化
無関係な違い(属性の順序、CDATA)にもかかわらず署名が再現できるよう、XML のノードのセットを安定したバイトへ変換するのが、canonical 化です。署名のためには、排他的な c14n(xml-exc-c14n)が好まれ、名前空間が署名されたサブツリーへスコープされるためです。
<!-- Two documents that are logically identical may differ in bytes:
- attribute order
- namespace declarations
- CDATA vs escaping
- whitespace outside elements
Canonical XML (c14n) produces a canonical byte form. -->
<CanonicalizationMethod
Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
<!-- Exclusive c14n (recommended for signatures): -->
<CanonicalizationMethod
Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
<!-- Exclusive form avoids leaking inherited namespace declarations
into the signed digest, preventing wrapping attacks. -->Enveloped 署名
署名する文書の内側に埋め込まれるのが(XML で最もよくある)、enveloped 署名です。ハッシュの前に <Signature> 要素を取り除くのが、enveloped-signature の transform で、署名が自身のダイジェストの一部になりません。Detached と enveloping のバリアントも存在します。
<?xml version="1.0"?>
<order Id="order">
<item>Widget</item>
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="...exc-c14n#"/>
<SignatureMethod Algorithm="...rsa-sha256"/>
<Reference URI="#order">
<Transforms>
<Transform Algorithm="...enveloped-signature"/>
</Transforms>
<DigestMethod Algorithm="...sha256"/>
<DigestValue>...</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>...</SignatureValue>
</Signature>
</order>
<!-- The signature lives INSIDE the signed element -->XLink と XPointer
XLink の単純リンク
任意の XML で HTML のアンカーを模倣するのが、XLink の単純リンクです。基本的な一方向のリンクを作るのが、xlink:type='simple' で、ターゲットであるのが、xlink:href です。表示を制御するのが(new/replace/embed)、show で、タイミングを制御するのが(onRequest/onLoad)、actuate です。
<?xml version="1.0"?>
<root xmlns:xlink="http://www.w3.org/1999/xlink">
<web xlink:type="simple"
xlink:href="https://example.com"
xlink:role="https://example.com/roles/home"
xlink:title="Example Site"
xlink:show="new"
xlink:actuate="onRequest">
Visit Example
</web>
</root>
<!-- A simple link is a one-way hyperlink, similar to HTML <a> -->XLink の拡張リンク
複数のリソース(ロケータ)を arc 経由で接続するのが、拡張リンクです。ラベルを各ロケータが持ち、ラベルの間の走査を定義するのが(from/to)、arcs です。別の文書に住めるのが、行外のリンクで、サードパーティのリソースの間の多方向のリンクを可能にします。
<?xml version="1.0"?>
<root xmlns:xlink="http://www.w3.org/1999/xlink">
<link xlink:type="extended" xlink:role="https://example.com/mapping">
<loc xlink:type="locator" xlink:label="src"
xlink:href="https://a.example/doc1" xlink:title="Doc A"/>
<loc xlink:type="locator" xlink:label="dst"
xlink:href="https://b.example/doc2" xlink:title="Doc B"/>
<go xlink:type="arc" xlink:from="src" xlink:to="dst"
xlink:show="new" xlink:actuate="onRequest"/>
</link>
</root>
<!-- Extended links can connect multiple resources and be out-of-line -->XLink の属性
タイプにより区画されるのが、XLink の属性です。ロケータ/リソースを狙うのが、href で、arcs のための参加者を名付けるのが、label、arc を配線するのが、from/to、セマンティックな URI(多くの場合 Dublin Core か RELAX NG の用語)であるのが、role/arcrole です。表示とローディングの挙動を駆動するのが、show/actuate です。
<!-- xlink:type: simple | extended | locator | arc | resource | title | none -->
<!-- Common attributes by type -->
<el xlink:type="simple" xlink:href="..." xlink:role="..." xlink:title="..."
xlink:show="new|replace|embed|other|none"
xlink:actuate="onRequest|onLoad|other|none"/>
<el xlink:type="locator" xlink:href="..." xlink:label="..." xlink:role="..."/>
<el xlink:type="arc" xlink:from="..." xlink:to="..." xlink:show="..."/>
<el xlink:type="resource" xlink:label="..." xlink:role="..."/>
<!-- xlink:role is a URI identifying the resource's meaning -->
<!-- xlink:arcrole describes the arc (relationship) itself -->XPointer の基本
URI のフラグメント経由で、XML 文書内の位置をアドレスするのが、XPointer です。ID により選択するのが、省略形(#id)で、XPath を使うのが、スキームベースの形式(#xpointer(...))、位置的な子のパスを使うのが、element() です。文書を取得した後に解釈されるのが、フラグメントです。
<?xml version="1.0"?>
<root xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- XPointer extends a URI fragment to address XML parts -->
<link xlink:type="simple"
xlink:href="doc.xml#xpointer(//book[@id='b1'])"/>
<link xlink:href="doc.xml#xpointer(/root/section[2]/p[1])"/>
<link xlink:href="doc.xml#b1"/>
</root>
<!-- Fragment forms:
- shorthand: #id
- scheme-based: #xpointer(expr)
- element(): #element(/1/2/3) -->XPointer のフレームワーク
複数のスキームが連鎖でき、早いものが失敗すれば、後のものが試されるのが、XPointer のフレームワークです。後続の xpointer() の式で使われるための接頭辞をバインドするのが、xmlns() のスキームです。ID に依存しない頑健な位置的なパスを与えるのが、element() です。
<!-- The XPointer Framework defines how fragment schemes compose -->
<ref xlink:href="doc.xml#element(/1/2)"/>
<ref xlink:href="doc.xml#xpointer(//section[@id='s1']/p[2])"/>
<ref xlink:href="doc.xml#xmlns(bk=https://example.com/b)xpointer(//bk:book)"/>
<!-- Multiple schemes can be tried in order: -->
<ref xlink:href="doc.xml#element(/1/2)xpointer(//book[@id='b1'])"/>
<!-- If element() fails, the next scheme is attempted -->
<!-- Common schemes: element(), xpointer(), xmlns(), xpath1() -->element() スキーム
1 ベースの子の位置のシーケンスによりノードをアドレスするのが、element() スキームで、オプションで ID 付きの要素から始まります。スキーマの変化に対し xpointer() より頑健です。要素の名前に依存せず — 構造だけに依存するからです。
<!-- element() addresses by child positions from the root -->
<ref xlink:href="doc.xml#element(/1/2/3)"/>
<!-- selects the 1st child of root, its 2nd child, then 3rd child -->
<!-- or relative to an ID -->
<ref xlink:href="doc.xml#element(b1/2)"/>
<!-- the 2nd child of the element with id="b1" -->
<!-- child positions are 1-based and skip text/attribute nodes;
only element children are counted -->命名の規約
要素の命名
スタイルを選び、一貫して適用しましょう。XML の語彙(HTML、SVG)でよくあるのが、ハイフン付きの小文字です。あいまいでない程度に記述的だが、簡潔であるべきなのが、名前です。暗号的な省略と過度に冗長な名前を避けましょう。
<!-- Good: lowercase, hyphen-separated, descriptive -->
<customer-address>
<street>123 Main St</street>
<postal-code>12345</postal-code>
</customer-address>
<!-- Avoid: abbreviations that are unclear -->
<!-- <cust-addr><pc>...</pc></cust-addr> -->
<!-- Avoid: too long -->
<!-- <customerMailingPostalAddressCode> -->
<!-- Be consistent across the whole vocabulary -->属性の命名
メタデータ(id、タイプ、href、status)に適するのが、属性です。要素の命名スタイルに一致させましょう。明示的な値を運ぶのが、ブールです。属性にその要素の名前を接頭してはいけません(<user> 上の user-id は冗長です)。一意の識別子には「id」を使いましょう。
<product sku="A1" unit-price="9.99" in-stock="true">
<name>Widget</name>
</product>
<!-- Conventions:
- attributes are metadata: id, type, href, status
- use lowercase-hyphen style to match elements
- boolean attributes still carry a value ("true"/"false")
- avoid repeating the element name: <user user-id="..."/>
prefer <user id="..."/> -->
<!-- IDs: use 'id' or '<element>-id' for clarity -->名前空間の URI と接頭辞
識別子であり取得可能な URL でないのが、名前空間の URI ですが、安定し所有されるべきです(制御するドメインで HTTPS を使いましょう)。ローカルのエイリアスであるのが、接頭辞で — 短く慣習的に保ちましょう。スキーマが非互換に変わるとき、URI をバージョン管理しましょう。
<!-- Namespace URIs should be stable, owned, and permanent -->
xmlns:bk = "https://example.com/ns/books/2024"
xmlns:auth= "https://example.com/ns/auth"
<!-- Prefix conventions:
- short and mnemonic: xs, xsi, xsl, svg, html, dc
- lowercase, no punctuation beyond letters
- 'tns' commonly means 'this namespace' in XSD
- avoid 'xml' (reserved) -->
<!-- Version the URI when the vocabulary changes incompatibly:
.../ns/books/2024 vs .../ns/books/2025 -->ケーススタイル
よくある XML のケーススタイル:PascalCase(XSD/WSDL、.NET)、camelCase(JSON 由来、Java)、ハイフン付き小文字(HTML/SVG、REST フレンドリー)、snake_case(まれ)です。重要な規則が、語彙内の一貫性です — スタイルの混合が混乱します。
<!-- PascalCase (UpperCamelCase): common in XSD/WSDL, .NET -->
<OrderRequest>
<CustomerId>123</CustomerId>
</OrderRequest>
<!-- camelCase: common in JSON-derived XML, Java ecosystems -->
<orderRequest>
<customerId>123</customerId>
</orderRequest>
<!-- lowercase-with-hyphens: HTML5, SVG, REST-friendly -->
<order-request>
<customer-id>123</customer-id>
</order-request>
<!-- snake_case: rare in XML, used in some Python/SQL ecosystems -->
<order_request><customer_id>123</customer_id></order_request>バージョン管理
明示的に XML の語彙をバージョン管理しましょう:ルート上の version 属性が最も簡単で、バージョン付きの名前空間の URI が最も厳密です(非互換の変更が新しい URI を得ます)。マイナー(追加的)対メジャー(破壊的)の変更が何を数えるか決め、文書化しましょう。
<!-- Versioning strategies -->
<!-- 1. Attribute on the root -->
<catalog version="2.0">...</catalog>
<!-- 2. Versioned namespace URI -->
<catalog xmlns="https://example.com/ns/catalog/v2">...</catalog>
<!-- 3. Versioned root element name -->
<catalog-v2>...</catalog-v2>
<!-- Backward-compatible changes: add optional elements/attributes
Incompatible changes: bump the version (and/or namespace) -->
<!-- Document the policy: which changes are "minor" vs "major" -->ファイルと拡張子の規約
認知された拡張子を使いましょう。そうすれば、ツールと人がファイルタイプを特定します。実際のバイトのエンコーディングに一致すべきなのが、XML 宣言の encoding 属性で、安全なデフォルトが、UTF-8 です。UTF-8 の XML には、BOM が非推奨です。
<!-- Common file extensions:
.xml generic XML
.xsd XML Schema
.xsl XSLT stylesheet
.xslt XSLT (alternate)
.dtd Document Type Definition
.rss RSS feed
.atom Atom feed
.svg SVG graphic
.wsdl WSDL service description
.xhtml XHTML document
.plist Apple property list -->
<!-- XML files are UTF-8 by default; declare encoding if different:
<?xml version="1.0" encoding="UTF-8"?> -->ベストプラクティス
まず Well-formed 性
任意のツールが処理する前に、文書が well-formed でなければなりません。早くパーサーで検証しましょう:最初のエラーを報告するのが、xmllint --noout file.xml です。交渉の余地がないのが、well-formed 性です。スキーマに対する validity が、追加のオプションのレイヤーです。
<?xml version="1.0" encoding="UTF-8"?>
<root>
<child>properly nested & escaped</child>
</root>
<!-- Always ensure well-formedness before worrying about validity:
- exactly one root element
- all tags closed and properly nested
- attributes quoted and unique per element
- & < escaped (and > in some contexts)
- valid encoding declaration -->検証とスキーマ
構造のエラーを捉えるため、スキーマに対して検証しましょう。型付きの名前空間の語彙で最もよくある選択が、XSD で、ビジネスルールで 補完するのが、Schematron です。文書をその XSD へリンクするのが、xsi:noNamespaceSchemaLocation で、名前空間のスキーマには、xsi:schemaLocation を使いましょう。
<!-- Choose a schema language:
- DTD: simple, built-in, limited types
- XSD: rich types, namespaces, industry standard
- RelaxNG: compact syntax, flexible patterns
- Schematron: rule-based business constraints -->
<?xml version="1.0"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="schema.xsd">
<item>valid</item>
</root>
<!-- Validate during development; consider it at runtime for
untrusted input. -->エンコーディング(UTF-8)
XML のデフォルトで推奨されるエンコーディングであるのが、UTF-8 です — エンティティなしで、すべての Unicode を扱います。常にエンコーディングを宣言し、そのエンコーディングでファイルを保存しましょう。BOM を避けましょう。特殊文字のためには、数値の文字参照も使えます。
<?xml version="1.0" encoding="UTF-8"?>
<root>
<msg>Café — résumé — 中文 — emoji 🙂</msg>
</root>
<!-- Always declare UTF-8 and save the file as UTF-8.
Avoid legacy encodings (ISO-8859-1) unless required.
Do not add a UTF-8 BOM (some parsers mishandle it).
For non-UTF-8 encodings, declare them accurately. -->読みやすさとインデント
一貫したインデント(2 スペースがよくある)が、XML を読みやすく、diff をきれいにします。長い単一行を避けましょう。空白を正規化できるのが、「xmllint --format」や XML フォーマッタのようなツールです — しかし、xml:space='preserve' の領域が再フォーマットされてはならないことに注意しましょう。
<?xml version="1.0"?>
<catalog>
<book id="b1">
<title>XML Guide</title>
<author>Jane Doe</author>
</book>
<book id="b2">
<title>Advanced XML</title>
<author>John Smith</author>
</book>
</catalog>
<!-- Use 2-space indentation; one element per line for mixed
or deep structures. Tools: xmllint --format, prettier. -->パフォーマンス
大きなファイルのためには、メモリを低く保つため、DOM よりストリーミングのパーサー(SAX/StAX)を優先しま しょう。必要でない限り、DTD のロードと外部エンティティを無効化しましょう。XPath の式を一度コンパイルし、再利用しましょう。内部のシステムのためには、サイズとパース時間を削減する、コンパクトなバイナリ形式を考えましょう。
<!-- Parsing large XML efficiently:
- use SAX/StAX (streaming) instead of DOM for big files
- disable DTD/external entities if you don't need them
- validate once, not on every read
- reuse parser instances (factory creation is costly)
- consider binary formats (protobuf, CBOR) for internal traffic -->
<!-- Java StAX with XXE disabled:
factory.setProperty(XMLInputFactory.SUPPORT_DTD, false); -->
<!-- For repeated XPath, compile once and reuse the expression -->セキュリティ(XXE)
DTD の外部エンティティを悪用し、ファイルを読み、SSRF を引き起こし、サービス拒否を引き起こすのが(billion laughs/entity expansion)、XML External Entity(XXE)攻撃です。最も強力な防御が、ユースケースが必要としない限り、DTD と外部エンティティの解決を完全に無効化することです。
<?xml version="1.0"?>
<!DOCTYPE root [
<!-- XXE: attacker forces the parser to read a local file -->
<!ENTITY xxe SYSTEM "file:///etc/passwd">
]>
<root>&xxe;</root>
<!-- Defenses (do ALL that apply):
1. Disable DTDs entirely if you don't need them.
2. Disable external entity resolution.
3. Disable XInclude.
4. Validate input; limit entity expansion (billion laughs). -->
<!-- Python: defusedxml
Java: XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES = false
PHP: libxml_disable_entity_loader(true) -->関連する XML スニペット
Copy-paste ready code for common tasks.
Namespaces
Declare and use XML namespaces.
XPath
Path expressions for selecting nodes.
DTD and Schema
Document Type Definition for validation.
DOM and SAX Parsing
Two models for reading XML.
Attributes
Name-value pairs on elements.
CDATA Sections
Escape blocks of literal text.
XSLT
Transform XML into other formats.
Well-Formed XML
Rules every parser enforces.
Was this helpful?