diff options
author | Masahiro FUJIMOTO <mfujimot@gmail.com> | 2021-06-02 23:47:55 +0900 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-06-02 23:47:55 +0900 |
commit | d671972ba9c48fa9367d6264b5d99151fc07235a (patch) | |
tree | 0f77577f5018e0011d949ddbf30acdd0eadd7979 /files/ja/conflicting | |
parent | 90e42d68d03a3ee0ab3b1e2728826977800b56c9 (diff) | |
download | translated-content-d671972ba9c48fa9367d6264b5d99151fc07235a.tar.gz translated-content-d671972ba9c48fa9367d6264b5d99151fc07235a.tar.bz2 translated-content-d671972ba9c48fa9367d6264b5d99151fc07235a.zip |
Web/XPath/Introduction_to_using_XPath_in_JavaScript の conflicting 版を削除 (#973)
conflicting に同じ文書の翻訳が2つ登録されていますが、翻訳カバー率や翻訳品質で正規の位置にある版が最も良いと思われるので、 conflicting の2つの翻訳は削除を提案します。
Diffstat (limited to 'files/ja/conflicting')
2 files changed, 0 insertions, 508 deletions
diff --git a/files/ja/conflicting/web/xpath/introduction_to_using_xpath_in_javascript/index.html b/files/ja/conflicting/web/xpath/introduction_to_using_xpath_in_javascript/index.html deleted file mode 100644 index 7b1bbbfe5a..0000000000 --- a/files/ja/conflicting/web/xpath/introduction_to_using_xpath_in_javascript/index.html +++ /dev/null @@ -1,412 +0,0 @@ ---- -title: JavaScript で XPath を使用する -slug: conflicting/Web/XPath/Introduction_to_using_XPath_in_JavaScript -translation_of: Web/XPath/Introduction_to_using_XPath_in_JavaScript -original_slug: Web/JavaScript/Introduction_to_using_XPath_in_JavaScript ---- -<p>このドキュメントでは、JavaScript の内部、拡張機能、そして Web サイトから <a href="/ja/docs/Web/XPath">XPath</a> を使用するためのインターフェイスについて説明します。Mozilla は <a class="external" href="https://www.w3.org/TR/2004/NOTE-DOM-Level-3-XPath-20040226/">DOM 3 XPath</a> をかなりの量実装しており、XPath 式は HTML と XML ドキュメントの両方に対して実行できます。</p> - -<p>XPath を使用するための主なインターフェースは、<a href="/ja/docs/Web/API/Document">Document</a> オブジェクトの <a href="/ja/docs/Web/API/Document/evaluate">evaluate</a> 関数です。</p> - -<h2 id="document.evaluate" name="document.evaluate">document.evaluate</h2> - -<p>このメソッドは、<a href="/ja/docs/Glossary/XML">XML</a> ベースのドキュメント (HTML ドキュメントを含む) に対して <a href="/ja/docs/Web/XPath">XPath</a> 式を評価し、<code><a href="/ja/docs/Web/API/XPathResult">XPathResult</a></code> オブジェクトを返します。このメソッドの既存のドキュメントは <a href="/ja/docs/Web/API/Document/evaluate">document.evaluate</a> にありますが、今のところ我々が必要としているものには乏しいです。</p> - -<pre class="brush: js notranslate">var xpathResult = document.evaluate( xpathExpression, contextNode, namespaceResolver, resultType, result ); -</pre> - -<h3 id="Parameters" name="Parameters">Parameters</h3> - -<p><a href="/ja/docs/Web/API/Document/evaluate">evaluate</a> 関数は合計5つのパラメータを取ります。</p> - -<ul> - <li><code>xpathExpression</code>: 評価される XPath 式を含む文字列</li> - <li><code>contextNode</code>: <code>xpathExpression</code> が評価されるべきドキュメント内のノード。<a href="/ja/docs/Web/API/Document">Document</a> ノードが最も一般的に使用されます</li> - <li><code>namespaceResolver</code>: <code>xpathExpression</code> 内に含まれる名前空間接頭辞を渡す関数で、その接頭辞に関連付けられた名前空間 URI を表す文字列を返します。これにより、XPath 式で使用されている接頭辞とドキュメント内で使用されている可能性のある異なる接頭辞との変換が可能になります。この関数は、以下のいずれかの方法で利用できます - <ul> - <li><code><a href="/ja/docs/Using_XPath#Node-specific_evaluator_function" title="en/XPathEvaluator">XPathEvaluator</a></code> オブジェクトの <code><a href="/ja/docs/Web/API/Document/createNSResolver">createNSResolver</a></code> メソッドを使用して<a href="/ja/docs/Web/JavaScript/Introduction_to_using_XPath_in_JavaScript#Implementing_a_Default_Namespace_Resolver">作成します</a>。事実上、これを使用する必要があります</li> - <li><code>null</code>です。これは、HTML ドキュメントや名前空間プレフィックスが使用されていない場合に使用することができます。<code>xpathExpression</code>に 名前空間プレフィックスが含まれている場合、<code>NAMESPACE_ERR</code> というコードで <code>DOMException</code> がスローされることに注意してください</li> - <li>カスタムのユーザ定義関数。詳細は、付録の <a href="/ja/docs/Web/JavaScript/Introduction_to_using_XPath_in_JavaScript#Implementing_a_User_Defined_Namespace_Resolver">ユーザー定義名前空間リゾルバの使用法</a> を参照してください</li> - </ul> - </li> - <li><code>resultType</code>: 評価の結果として返される結果の型を指定する<a href="/ja/docs/Web/JavaScript/Introduction_to_using_XPath_in_JavaScript#XPathResult_Defined_Constants">定数</a>です。最も一般的に渡される定数は <code>XPathResult.ANY_TYPE</code> で、これは XPath 式の結果を最も自然な型として返します。付録には、<a href="/ja/docs/Web/JavaScript/Introduction_to_using_XPath_in_JavaScript#XPathResult_Defined_Constants">利用可能な定数</a>の完全なリストを含むセクションがあります。これらの定数は以下の「<a href="/ja/docs/Web/JavaScript/Introduction_to_using_XPath_in_JavaScript#Specifying_the_Return_Type">戻り値の型の指定</a>」のセクションで説明されています</li> - <li><code>result</code>: 既存の <code>XPathResult</code> オブジェクトを指定すると、そのオブジェクトが再利用されて結果が返されます。<code>null</code> を指定すると、新しい <code>XPathResult</code> オブジェクトが作成されます</li> -</ul> - -<h3 id="Return_Value" name="Return_Value">Return Value</h3> - -<p><code>resultType</code> パラメータで<a href="/ja/docs/Web/JavaScript/Introduction_to_using_XPath_in_JavaScript#Specifying_the_Return_Type">指定された</a>型の <code>XPathResult</code> オブジェクトを返します。<code>XPathResult</code> インターフェースは<a href="/ja/docs/Web/API/XPathResult">ここ</a>で定義されています。</p> - -<h3 id="Implementing_a_Default_Namespace_Resolver" name="Implementing_a_Default_Namespace_Resolver">Implementing a Default Namespace Resolver</h3> - -<p><a href="/ja/docs/Web/API/document" title="en/DOM/document">document</a> オブジェクトの <code>createNSResolver</code> メソッドを使用して名前空間リゾルバを作成します。</p> - -<pre class="brush: js notranslate">var nsResolver = document.createNSResolver( contextNode.ownerDocument == null ? contextNode.documentElement : contextNode.ownerDocument.documentElement ); -</pre> - -<p><span class="comment">Or alternatively by using the <code>createNSResolver</code> method of a <code>XPathEvaluator</code> object. <pre> var xpEvaluator = new XPathEvaluator(); var nsResolver = xpEvaluator.createNSResolver( contextNode.ownerDocument == null ? contextNode.documentElement : contextNode.ownerDocument.documentElement ); </pre></span> そして、<code>namespaceResolver</code> パラメータとして <code>nsResolver</code> 変数である <code>document.evaluate</code> を渡します。</p> - -<p>注意: XPath は、ヌル名前空間の要素にのみマッチするように、接頭辞のない QNames を定義しています。XPath では、通常の要素参照 (例: <code><span class="nowiki">xmlns='http://www.w3.org/1999/xhtml</span>'</code> の <code>p[@id='_myid']</code>) に適用されるデフォルトの名前空間を拾う方法はありません。NULL ではない名前空間のデフォルト要素にマッチさせるには、<code>['namespace-uri()='<span class="nowiki">http://www.w3.org/1999/xhtml</span>' and name()='p' and @id='_myid']</code> のような形式を使用して特定の要素を参照する必要があります (<a href="/ja/docs/Web/JavaScript/Introduction_to_using_XPath_in_JavaScript#Using_XPath_functions_to_reference_elements_with_a_default_namespace">このアプローチ</a>は、名前空間がわからない動的な XPath の場合にうまく機能します)。後者の方法を取りたい場合は、<a href="/ja/docs/Web/JavaScript/Introduction_to_using_XPath_in_JavaScript#Implementing_a_User_Defined_Namespace_Resolver">ユーザ定義の名前空間リゾルバを作成する方法</a>を参照してください。</p> - -<h3 id="Notes" name="Notes">Notes</h3> - -<p>任意の DOM ノードを名前空間を解決するように適応させ、 <a href="/ja/docs/Web/XPath">XPath</a> 式をドキュメント内で出現したノードのコンテキストからの相対評価を簡単に行えるようにします。このアダプタは、ノード上の DOM Level 3 メソッド <code>lookupNamespaceURI</code> と同様に動作し、 <code>lookupNamespaceURI</code> が呼び出された時点でのノードの階層内で利用可能な現在の情報を使用して、指定したプレフィックスから <code>namespaceURI</code> を解決します。また、暗黙の <code>xml</code> 接頭辞も正しく解決します。</p> - -<h3 id="Specifying_the_Return_Type" name="Specifying_the_Return_Type">Specifying the Return Type</h3> - -<p>The returned variable <code>xpathResult</code> from <code>document.evaluate</code> can either be composed of individual nodes (<a href="#Simple_Types">simple types</a>), or a collection of nodes (<a href="#Node-Set_Types">node-set types</a>).</p> - -<h4 id="Simple_Types" name="Simple_Types">Simple Types</h4> - -<p><code>resultType</code> に希望する結果タイプがどちらかに指定されている場合。</p> - -<ul> - <li><code>NUMBER_TYPE</code> - a double</li> - <li><code>STRING_TYPE</code> - 文字列</li> - <li><code>BOOLEAN_TYPE</code> - 真偽値</li> -</ul> - -<p><code>XPathResult</code> オブジェクトの以下のプロパティにそれぞれアクセスして、式の戻り値を取得します。</p> - -<ul> - <li><code>numberValue</code></li> - <li><code>stringValue</code></li> - <li><code>booleanValue</code></li> -</ul> - -<h5 id="Example" name="Example">Example</h5> - -<p>The following uses the XPath expression <code><a href="/en-US/docs/XPath/Functions/count" title="en/XPath/Functions/count">count(//p)</a></code> to obtain the number of <code><p></code> elements in an HTML document:</p> - -<pre class="brush: js notranslate">var paragraphCount = document.evaluate( 'count(//p)', document, null, XPathResult.ANY_TYPE, null ); - -alert( 'This document contains ' + paragraphCount.numberValue + ' paragraph elements' ); -</pre> - -<p>Although JavaScript allows us to convert the number to a string for display, the XPath interface will not automatically convert the numerical result if the <code>stringValue</code> property is requested, so the following code will <strong>not</strong> work:</p> - -<pre class="brush: js notranslate">var paragraphCount = document.evaluate('count(//p)', document, null, XPathResult.ANY_TYPE, null ); - -alert( 'This document contains ' + paragraphCount.stringValue + ' paragraph elements' ); -</pre> - -<p>Instead, it will return an exception with the code <code>NS_DOM_TYPE_ERROR</code>.</p> - -<h4 id="Node-Set_Types" name="Node-Set_Types">Node-Set Types</h4> - -<p>The <code>XPathResult</code> object allows node-sets to be returned in 3 principal different types:</p> - -<ul> - <li><a href="#Iterators">Iterators</a></li> - <li><a href="#Snapshots">Snapshots</a></li> - <li><a href="#First_Node">First Nodes</a></li> -</ul> - -<h5 id="Iterators" name="Iterators">Iterators</h5> - -<p>When the specified result type in the <code>resultType</code> parameter is either:</p> - -<ul> - <li><code>UNORDERED_NODE_ITERATOR_TYPE</code></li> - <li><code>ORDERED_NODE_ITERATOR_TYPE</code></li> -</ul> - -<p>The <code>XPathResult</code> object returned is a node-set of matched nodes which will behave as an iterator, allowing us to access the individual nodes contained by using the <code>iterateNext()</code> method of the <code>XPathResult</code>.</p> - -<p>Once we have iterated over all of the individual matched nodes, <code>iterateNext()</code> will return <code>null</code>.</p> - -<p>Note however, that if the document is mutated (the document tree is modified) between iterations that will invalidate the iteration and the <code>invalidIteratorState</code> property of <code>XPathResult</code> is set to <code>true</code>, and a <code>NS_ERROR_DOM_INVALID_STATE_ERR</code> exception is thrown.</p> - -<h6 id="Iterator_Example" name="Iterator_Example">Iterator Example</h6> - -<pre class="brush: js notranslate">var iterator = document.evaluate('//phoneNumber', documentNode, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null ); - -try { - var thisNode = iterator.iterateNext(); - - while (thisNode) { - alert( thisNode.textContent ); - thisNode = iterator.iterateNext(); - } -} -catch (e) { - alert( 'Error: Document tree modified during iteration ' + e ); -} -</pre> - -<h5 id="Snapshots" name="Snapshots">Snapshots</h5> - -<p>When the specified result type in the <code>resultType</code> parameter is either:</p> - -<ul> - <li><code>UNORDERED_NODE_SNAPSHOT_TYPE</code></li> - <li><code>ORDERED_NODE_SNAPSHOT_TYPE</code></li> -</ul> - -<p>The <code>XPathResult</code> object returned is a static node-set of matched nodes, which allows us to access each node through the <code>snapshotItem(itemNumber)</code> method of the <code>XPathResult</code> object, where <code>itemNumber</code> is the index of the node to be retrieved. The total number of nodes contained can be accessed through the <code>snapshotLength</code> property.</p> - -<p>Snapshots do not change with document mutations, so unlike the iterators, the snapshot does not become invalid, but it may not correspond to the current document, for example, the nodes may have been moved, it might contain nodes that no longer exist, or new nodes could have been added.</p> - -<h6 id="Snapshot_Example" name="Snapshot_Example">Snapshot Example</h6> - -<pre class="brush: js notranslate">var nodesSnapshot = document.evaluate('//phoneNumber', documentNode, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null ); - -for ( var i=0 ; i < nodesSnapshot.snapshotLength; i++ ) -{ - alert( nodesSnapshot.snapshotItem(i).textContent ); -} -</pre> - -<h5 id="First_Node" name="First_Node">First Node</h5> - -<p>When the specified result type in the <code>resultType</code> parameter is either:</p> - -<ul> - <li><code>ANY_UNORDERED_NODE_TYPE</code></li> - <li><code>FIRST_ORDERED_NODE_TYPE</code></li> -</ul> - -<p>The <code>XPathResult</code> object returned is only the first found node that matched the XPath expression. This can be accessed through the <code>singleNodeValue</code> property of the <code>XPathResult</code> object. This will be <code>null</code> if the node set is empty.</p> - -<p>Note that, for the unordered subtype the single node returned might not be the first in document order, but for the ordered subtype you are guaranteed to get the first matched node in the document order.</p> - -<h6 id="First_Node_Example" name="First_Node_Example">First Node Example</h6> - -<pre class="brush: js notranslate">var firstPhoneNumber = document.evaluate('//phoneNumber', documentNode, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ); - -alert( 'The first phone number found is ' + firstPhoneNumber.singleNodeValue.textContent ); -</pre> - -<h4 id="The_ANY_TYPE_Constant" name="The_ANY_TYPE_Constant">The ANY_TYPE Constant</h4> - -<p>When the result type in the <code>resultType</code> parameter is specified as <code>ANY_TYPE</code>, the <code>XPathResult</code> object returned, will be whatever type that naturally results from the evaluation of the expression.</p> - -<p>It could be any of the simple types (<code>NUMBER_TYPE, STRING_TYPE, BOOLEAN_TYPE</code>), <strong>but</strong>, if the returned result type is a node-set then it will <strong>only</strong> be an <code>UNORDERED_NODE_ITERATOR_TYPE</code>.</p> - -<p>To determine that type after evaluation, we use the <code>resultType</code> property of the <code>XPathResult</code> object. The <a href="#XPathResult_Defined_Constants">constant</a> values of this property are defined in the appendix. <span class="comment">None Yet =====Any_Type Example===== <pre> </pre></span></p> - -<h2 id="Examples" name="Examples">Examples</h2> - -<h3 id="Within_an_HTML_Document" name="Within_an_HTML_Document">Within an HTML Document</h3> - -<p>The following code is intended to be placed in any JavaScript fragment within or linked to the HTML document against which the XPath expression is to be evaluated.</p> - -<p>To extract all the <code><h2></code> heading elements in an HTML document using XPath, the <code>xpathExpression</code> is simply '<code>//h2</code>'. Where, <code>//</code> is the Recursive Descent Operator that matches elements with the nodeName <code>h2</code> anywhere in the document tree. The full code for this is: <span class="comment">link to introductory xpath doc</span></p> - -<pre class="brush: js notranslate">var headings = document.evaluate('//h2', document, null, XPathResult.ANY_TYPE, null ); -</pre> - -<p>Notice that, since HTML does not have namespaces, we have passed <code>null</code> for the <code>namespaceResolver</code> parameter.</p> - -<p>Since we wish to search over the entire document for the headings, we have used the <a href="/en-US/docs/Web/API/document" title="en/DOM/document">document</a> object itself as the <code>contextNode</code>.</p> - -<p>The result of this expression is an <code>XPathResult</code> object. If we wish to know the type of result returned, we may evaluate the <code>resultType</code> property of the returned object. In this case, that will evaluate to <code>4</code>, an <code>UNORDERED_NODE_ITERATOR_TYPE</code>. This is the default return type when the result of the XPath expression is a node set. It provides access to a single node at a time and may not return nodes in a particular order. To access the returned nodes, we use the <code>iterateNext()</code> method of the returned object:</p> - -<pre class="brush: js notranslate">var thisHeading = headings.iterateNext(); - -var alertText = 'Level 2 headings in this document are:\n' - -while (thisHeading) { - alertText += thisHeading.textContent + '\n'; - thisHeading = headings.iterateNext(); -} -</pre> - -<p>Once we iterate to a node, we have access to all the standard DOM interfaces on that node. After iterating through all the <code>h2</code> elements returned from our expression, any further calls to <code>iterateNext()</code> will return <code>null</code>.</p> - -<h3 id="Evaluating_against_an_XML_document_within_an_Extension" name="Evaluating_against_an_XML_document_within_an_Extension">Evaluating against an XML document within an Extension</h3> - -<p>The following uses an XML document located at <span class="nowiki">chrome://yourextension/content/peopleDB.xml</span> as an example.</p> - -<pre class="brush: xml notranslate"><?xml version="1.0"?> -<people xmlns:xul = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" > - <person> - <name first="george" last="bush" /> - <address street="1600 pennsylvania avenue" city="washington" country="usa"/> - <phoneNumber>202-456-1111</phoneNumber> - </person> - <person> - <name first="tony" last="blair" /> - <address street="10 downing street" city="london" country="uk"/> - <phoneNumber>020 7925 0918</phoneNumber> - </person> -</people> -</pre> - -<p>To make the contents of the XML document available within the extension, we create an <code><a href="/en-US/docs/Web/API/XMLHttpRequest" title="en/XMLHttpRequest">XMLHttpRequest</a></code> object to load the document synchronously, the variable <code>xmlDoc</code> will contain the document as an <code><a href="/en-US/docs/Web/API/XMLDocument" title="en/XMLDocument">XMLDocument</a></code> object against which we can use the <code>evaluate</code> method</p> - -<p>JavaScript used in the extensions xul/js documents.</p> - -<pre class="brush: js notranslate">var req = new XMLHttpRequest(); - -req.open("GET", "chrome://yourextension/content/peopleDB.xml", false); -req.send(null); - -var xmlDoc = req.responseXML; - -var nsResolver = xmlDoc.createNSResolver( xmlDoc.ownerDocument == null ? xmlDoc.documentElement : xmlDoc.ownerDocument.documentElement); - -var personIterator = xmlDoc.evaluate('//person', xmlDoc, nsResolver, XPathResult.ANY_TYPE, null ); -</pre> - -<h3 id="Note">Note</h3> - -<p>When the XPathResult object is not defined, the constants can be retrieved in privileged code using <code>Components.interfaces.nsIDOMXPathResult.ANY_TYPE</code> (<code>CI.nsIDOMXPathResult</code>). Similarly, an XPathEvaluator can be created using:</p> - -<pre class="brush: js notranslate">Components.classes["@mozilla.org/dom/xpath-evaluator;1"].createInstance(Components.interfaces.nsIDOMXPathEvaluator)</pre> - -<h2 id="Appendix" name="Appendix">Appendix</h2> - -<h4 id="Implementing_a_User_Defined_Namespace_Resolver" name="Implementing_a_User_Defined_Namespace_Resolver">Implementing a User Defined Namespace Resolver</h4> - -<p>This is an example for illustration only. This function will need to take namespace prefixes from the <code>xpathExpression</code> and return the URI that corresponds to that prefix. For example, the expression:</p> - -<pre class="notranslate">'//xhtml:td/mathml:math' -</pre> - -<p>will select all <a href="/en-US/docs/Web/API/MathML" title="en/MathML">MathML</a> expressions that are the children of (X)HTML table data cell elements.</p> - -<p>In order to associate the '<code>mathml:</code>' prefix with the namespace URI '<code><span class="nowiki">http://www.w3.org/1998/Math/MathML</span></code>' and '<code>xhtml:</code>' with the URI '<code><span class="nowiki">http://www.w3.org/1999/xhtml</span></code>' we provide a function:</p> - -<pre class="brush: js notranslate">function nsResolver(prefix) { - var ns = { - 'xhtml' : 'http://www.w3.org/1999/xhtml', - 'mathml': 'http://www.w3.org/1998/Math/MathML' - }; - return ns[prefix] || null; -} -</pre> - -<p>Our call to <code>document.evaluate</code> would then looks like:</p> - -<pre class="brush: js notranslate">document.evaluate( '//xhtml:td/mathml:math', document, nsResolver, XPathResult.ANY_TYPE, null ); -</pre> - -<h4 id="Implementing_a_default_namespace_for_XML_documents" name="Implementing_a_default_namespace_for_XML_documents">Implementing a default namespace for XML documents</h4> - -<p>As noted in the <a href="#Implementing_a_Default_Namespace_Resolver">Implementing a Default Namespace Resolver</a> previously, the default resolver does not handle the default namespace for XML documents. For example with this document:</p> - -<pre class="brush: xml notranslate"><?xml version="1.0" encoding="UTF-8"?> -<feed xmlns="http://www.w3.org/2005/Atom"> - <entry /> - <entry /> - <entry /> -</feed> -</pre> - -<p><code>doc.evaluate('//entry', doc, nsResolver, XPathResult.ANY_TYPE, null)</code> will return an empty set, where <code>nsResolver</code> is the resolver returned by <code>createNSResolver</code>. Passing a <code>null</code> resolver doesn't work any better, either.</p> - -<p>One possible workaround is to create a custom resolver that returns the correct default namespace (the Atom namespace in this case). Note that you still have to use some namespace prefix in your XPath expression, so that the resolver function will be able to change it to your required namespace. E.g.:</p> - -<pre class="brush: js notranslate">function resolver() { - return 'http://www.w3.org/2005/Atom'; -} -doc.evaluate('//myns:entry', doc, resolver, XPathResult.ANY_TYPE, null) -</pre> - -<p>Note that a more complex resolver will be required if the document uses multiple namespaces.</p> - -<p>An approach which might work better (and allow namespaces not to be known ahead of time) is described in the next section.</p> - -<h4 id="Using_XPath_functions_to_reference_elements_with_a_default_namespace" name="Using_XPath_functions_to_reference_elements_with_a_default_namespace">Using XPath functions to reference elements with a default namespace</h4> - -<p>Another approach to match default elements in a non-null namespace (and one which works well for dynamic XPath expressions where the namespaces might not be known), involves referring to a particular element using a form such as <code>[namespace-uri()='<span class="nowiki">http://www.w3.org/1999/xhtml</span>' and name()='p' and @id='_myid']</code>. This circumvents the problem of an XPath query not being able to detect the default namespace on a regularly labeled element.</p> - -<h4 id="Getting_specifically_namespaced_elements_and_attributes_regardless_of_prefix" name="Getting_specifically_namespaced_elements_and_attributes_regardless_of_prefix">Getting specifically namespaced elements and attributes regardless of prefix</h4> - -<p>If one wishes to provide flexibility in namespaces (as they are intended) by not necessarily requiring a particular prefix to be used when finding a namespaced element or attribute, one must use special techniques.</p> - -<p>While one can adapt the approach in the above section to test for namespaced elements regardless of the prefix chosen (using <code><a href="/en-US/docs/XPath/Functions/local-name" title="en/XPath/Functions/local-name">local-name()</a></code> in combination with <code><a href="/en-US/docs/XPath/Functions/namespace-uri" title="en/XPath/Functions/namespace-uri">namespace-uri()</a></code> instead of <code><a href="/en-US/docs/XPath/Functions/name" title="en/XPath/Functions/name">name()</a></code>), a more challenging situation occurs, however, if one wishes to grab an element with a particular namespaced attribute in a predicate (given the absence of implementation-independent variables in XPath 1.0).</p> - -<p>For example, one might try (incorrectly) to grab an element with a namespaced attribute as follows: <code>var xpathlink = someElements[local-name(@*)="href" and namespace-uri(@*)='<span class="nowiki">http://www.w3.org/1999/xlink</span>'];</code></p> - -<p>This could inadvertently grab some elements if one of its attributes existed that had a local name of "<code>href</code>", but it was a different attribute which had the targeted (XLink) namespace (instead of <code><a href="/en/XPath/Axes/attribute" title="en/XPath/Axes/attribute">@href</a></code>).</p> - -<p>In order to accurately grab elements with the XLink <code>@href</code> attribute (without also being confined to predefined prefixes in a namespace resolver), one could obtain them as follows:</p> - -<pre class="brush: js notranslate">var xpathEls = 'someElements[@*[local-name() = "href" and namespace-uri() = "http://www.w3.org/1999/xlink"]]'; // Grabs elements with any single attribute that has both the local name 'href' and the XLink namespace -var thislevel = xml.evaluate(xpathEls, xml, null, XPathResult.ANY_TYPE, null); -var thisitemEl = thislevel.iterateNext(); -</pre> - -<h4 id="XPathResult_Defined_Constants" name="XPathResult_Defined_Constants">XPathResult Defined Constants</h4> - -<table class="standard-table"> - <thead> - <tr> - <td class="header">Result Type Defined Constant</td> - <td class="header">Value</td> - <td class="header">Description</td> - </tr> - </thead> - <tbody> - <tr> - <td>ANY_TYPE</td> - <td>0</td> - <td>A result set containing whatever type naturally results from the evaluation of the expression. Note that if the result is a node-set then UNORDERED_NODE_ITERATOR_TYPE is always the resulting type.</td> - </tr> - <tr> - <td>NUMBER_TYPE</td> - <td>1</td> - <td>A result containing a single number. This is useful for example, in an XPath expression using the <code>count()</code> function.</td> - </tr> - <tr> - <td>STRING_TYPE</td> - <td>2</td> - <td>A result containing a single string.</td> - </tr> - <tr> - <td>BOOLEAN_TYPE</td> - <td>3</td> - <td>A result containing a single boolean value. This is useful for example, in an XPath expression using the <code>not()</code> function.</td> - </tr> - <tr> - <td>UNORDERED_NODE_ITERATOR_TYPE</td> - <td>4</td> - <td>A result node-set containing all the nodes matching the expression. The nodes may not necessarily be in the same order that they appear in the document.</td> - </tr> - <tr> - <td>ORDERED_NODE_ITERATOR_TYPE</td> - <td>5</td> - <td>A result node-set containing all the nodes matching the expression. The nodes in the result set are in the same order that they appear in the document.</td> - </tr> - <tr> - <td>UNORDERED_NODE_SNAPSHOT_TYPE</td> - <td>6</td> - <td>A result node-set containing snapshots of all the nodes matching the expression. The nodes may not necessarily be in the same order that they appear in the document.</td> - </tr> - <tr> - <td>ORDERED_NODE_SNAPSHOT_TYPE</td> - <td>7</td> - <td>A result node-set containing snapshots of all the nodes matching the expression. The nodes in the result set are in the same order that they appear in the document.</td> - </tr> - <tr> - <td>ANY_UNORDERED_NODE_TYPE</td> - <td>8</td> - <td>A result node-set containing any single node that matches the expression. The node is not necessarily the first node in the document that matches the expression.</td> - </tr> - <tr> - <td>FIRST_ORDERED_NODE_TYPE</td> - <td>9</td> - <td>A result node-set containing the first node in the document that matches the expression.</td> - </tr> - </tbody> -</table> - -<h2 id="See_also" name="See_also">See also</h2> - -<ul> - <li><a href="/en-US/docs/Web/XPath">XPath</a></li> - <li><a href="http://www.xml.com/pub/a/2000/08/holman/index.html?page=2#xpath-info">XML Path Language </a>from <em><a href="http://www.xml.com/pub/a/2000/08/holman/">What is XSLT?</a> </em>by G. Ken Holman</li> -</ul> - -<div class="originaldocinfo"> -<h2 id="Original_Document_Information" name="Original_Document_Information">Original Document Information</h2> - -<ul> - <li>Based Upon Original Document <a class="external" href="http://www-xray.ast.cam.ac.uk/~jgraham/mozilla/xpath-tutorial.html">Mozilla XPath Tutorial</a></li> - <li>Original Source Author: James Graham.</li> - <li>Other Contributors: James Thompson.</li> - <li>Last Updated Date: 2006-3-25.</li> -</ul> -</div> diff --git a/files/ja/conflicting/web/xpath/introduction_to_using_xpath_in_javascript_caa7dfd0899fa1d0dfa5b1eb32e49ac7/index.html b/files/ja/conflicting/web/xpath/introduction_to_using_xpath_in_javascript_caa7dfd0899fa1d0dfa5b1eb32e49ac7/index.html deleted file mode 100644 index 1c3ebc7ca6..0000000000 --- a/files/ja/conflicting/web/xpath/introduction_to_using_xpath_in_javascript_caa7dfd0899fa1d0dfa5b1eb32e49ac7/index.html +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Using XPath -slug: >- - conflicting/Web/XPath/Introduction_to_using_XPath_in_JavaScript_caa7dfd0899fa1d0dfa5b1eb32e49ac7 -tags: - - AJAX - - Add-ons - - DOM - - Extensions - - Transforming_XML_with_XSLT - - XML - - XPath - - XSLT -translation_of: Web/XPath/Introduction_to_using_XPath_in_JavaScript -translation_of_original: Using_XPath -original_slug: Using_XPath ---- -<p> -</p><p><a href="ja/XPath">XPath</a> は XML 文書の一部を指し示すための言語であり、<a class="external" href="http://www.w3.org/TR/xpath">W3C 勧告</a>です。 -</p><p>この記事では JavaScript のコードから XPath の機能を使うための Mozilla のインターフェイスについて説明します。これらは <a class="external" href="http://www.w3.org/TR/DOM-Level-3-XPath/">DOM Level 3 XPath</a> (現時点では W3C Working Group Note) に記載されているものです。 -</p><p>この記事は XPath それ自体について教えるものではありません。XPath についてよく知らなければ、 <a class="external" href="http://www.w3schools.com/xpath/">W3Schools XPath tutorial</a> を参照して下さい。 -</p><p>{{ 英語版章題("Wrapper function") }} -</p> -<h3 id=".E3.83.A9.E3.83.83.E3.83.91.E9.96.A2.E6.95.B0">ラッパ関数</h3> -<p>次の関数を使うと、特定の XML ノードに対して XPath 式を評価する事ができます。第一引数は DOM ノードもしくは Document オブジェクトで、第二引数は XPath 式を定義した文字列です。 -</p> -<pre>// 特定の DOM ノードもしくは Document オブジェクト (aNode) に対して -// XPath 式 aExpression を評価し、その結果を配列として返す。 -// 最初の作業を行った wanderingstan at morethanwarm dot mail dot com に感謝します。 -function evaluateXPath(aNode, aExpr) { - var xpe = new XPathEvaluator(); - var nsResolver = xpe.createNSResolver(aNode.ownerDocument == null ? - aNode.documentElement : aNode.ownerDocument.documentElement); - var result = xpe.evaluate(aExpr, aNode, nsResolver, 0, null); - var found = []; - var res; - while (res = result.iterateNext()) - found.push(res); - return found; -} -</pre> -<p>この関数では <code>new XPathEvaluator()</code> を使用しています。このコンストラクタは Mozilla 固有のものです。他のブラウザで使用される可能性のある Web ページのスクリプトでは、 <code>new XPathEvaluator()</code> の呼び出しを次のコードに置き換えて下さい。 -</p> -<pre> // XPathEvaluator は Document を実装するオブジェクトに実装されている - var xpe = aNode.ownerDocument || aNode; -</pre> -<p>この場合、 <a href="ja/DOM/document.createNSResolver">XPathNSResolver</a> の作成は次のように単純にできます。 -</p> -<pre> var nsResolver = xpe.createNSResolver(xpe.documentElement); -</pre> -<p>ただ、 <code>createNSResolver</code> は、 XPath 式の中の名前空間接頭辞が検索対象の文書のものと一致する場合にしか使うべきではないということに注意してください。一致しない場合には、独自の XPathNSResolver の実装を用意しなければなりません。 -</p><p><a href="ja/XMLHttpRequest">XMLHttpRequest</a> を使って (<a href="ja/Parsing_and_serializing_XML">Parsing and serializing XML</a> にあるように) ローカルもしくはリモートの XML ファイルを DOM ツリーに読み込んだ場合には、 <code>evaluateXPath()</code> の第一引数に <code>req.responseXML</code> を指定します。 -</p><p>{{ 英語版章題("Sample usage") }} -</p> -<h3 id=".E4.BD.BF.E7.94.A8.E4.BE.8B">使用例</h3> -<p>次のような XML 文書があるとします。 (<a href="ja/How_to_create_a_DOM_tree">How to create a DOM tree</a> と <a href="ja/Parsing_and_serializing_XML">Parsing and serializing XML</a> も参照して下さい) -</p> -<pre><?xml version="1.0"?> -<people> - <person first-name="eric" middle-initial="H" last-name="jung"> - <address street="321 south st" city="denver" state="co" country="usa"/> - <address street="123 main st" city="arlington" state="ma" country="usa"/> - </person> - - <person first-name="jed" last-name="brown"> - <address street="321 north st" city="atlanta" state="ga" country="usa"/> - <address street="123 west st" city="seattle" state="wa" country="usa"/> - <address street="321 south avenue" city="denver" state="co" country="usa"/> - </person> -</people> -</pre> -<p>関数 <code>evaluateXPath</code> を使って、XPath 式でこの文書を「クエリ」する事ができます。DOM ツリーを走査しても同様の結果を得られますが、XPath 式を使った方がずっと高速で強力です。<code>id</code> 属性に頼る事ができれば <code>document.getElementById()</code> は強力ですが、XPath の強力さには全く及びません。いくつか例を示します。 -</p> -<pre>// 文書内の全ての人物の苗字を表示する -var results = evaluateXPath(people, "//person/@last-name"); -for (var i in results) - alert("Person #" + i + " has the last name " + results[i].value); - -// 2 人目の人物のノードを得る -results = evaluateXPath(people, "/people/person[2]"); - -// デンバーに住所を持つ全ての人物ノードを得る -results = evaluateXPath(people, "//person[address/@city='denver']"); - -// 通りの名前に "south" が含まれる全ての住所を得る -results = evaluateXPath(people, "//address[contains(@street, 'south')]"); -alert(results.length); -</pre> -<p>{{ 英語版章題("Resources") }} -</p> -<h3 id=".E8.B3.87.E6.96.99">資料</h3> -<ul> <li><a href="/ja/XPath" title="ja/XPath">XPath</a></li> <li><a class="external" href="http://www.topxml.com/code/default.asp?p=3&id=v20021221025528">XPath Visualizer for Mozilla and Firefox</a></li> <li><a class="external" href="http://www.w3schools.com/xpath/">XPath tutorial</a></li> <li><a class="external" href="http://forums.mozillazine.org/viewtopic.php?t=229106">この話題に関するフォーラムでの議論</a></li> <li><a class="external" href="http://zeus.jesus.cam.ac.uk/~jg307/mozilla/xpath-tutorial.html">Using the Mozilla JavaScript Interface to XPath</a> - JavaScript から XPath を使用するためのチュートリアルの草稿</li> -</ul> -<p> </p> - -<p>{{ languages( { "en": "en/Using_XPath", "fr": "fr/Utilisation_de_XPath", "ko": "ko/Using_XPath", "zh-cn": "cn/Using_XPath" } ) }}</p> |