Dom-xml-dom-clone-node

提供:Dev Guides
移動先:案内検索

XML DOM-クローンノード

この章では、XML DOMオブジェクトでの_Clone Node_操作について説明します。 ノードの複製操作を使用して、指定したノードの複製コピーを作成します。 _cloneNode()_はこの操作に使用されます。

cloneNode()

このメソッドは、このノードの複製を返します。つまり、ノードの汎用コピーコンストラクターとして機能します。 複製ノードには親がなく(parentNodeはnull)、ユーザーデータもありません。

構文

_cloneNode()_メソッドの構文は次のとおりです-

Node cloneNode(boolean deep)
  • deep-trueの場合、指定されたノードの下のサブツリーを再帰的に複製します。 falseの場合、ノード自体(および要素の場合はその属性)のみを複製します。
  • このメソッドは重複ノードを返します。

次の例(clonenode_example)は、XMLドキュメント(link:/dom/node.xml [node.xml])を解析してXML DOMオブジェクトに変換し、最初の_Employee_要素のディープコピーを作成します。

<!DOCTYPE html>
<html>
   <head>
      <script>
         function loadXMLDoc(filename) {
            if (window.XMLHttpRequest) {
               xhttp = new XMLHttpRequest();
            } else//code for IE5 and IE6 {
               xhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xhttp.open("GET",filename,false);
            xhttp.send();
            return xhttp.responseXML;
         }
      </script>
   </head>
   <body>
      <script>
         xmlDoc = loadXMLDoc("/dom/node.xml");

         x = xmlDoc.getElementsByTagName('Employee')[0];
         clone_node = x.cloneNode(true);
         xmlDoc.documentElement.appendChild(clone_node);

         firstname = xmlDoc.getElementsByTagName("FirstName");
         lastname = xmlDoc.getElementsByTagName("LastName");
     contact = xmlDoc.getElementsByTagName("ContactNo");
     email = xmlDoc.getElementsByTagName("Email");
         for (i = 0;i < firstname.length;i++) {
            document.write(firstname[i].childNodes[0].nodeValue+'
               '+lastname[i].childNodes[0].nodeValue+',
               '+contact[i].childNodes[0].nodeValue+',  '+email[i].childNodes[0].nodeValue);
            document.write("<br>");
         }
      </script>
   </body>
</html>

上記の例でわかるように、cloneNode() paramを_true_に設定しました。 したがって、_Employee_要素の下の各子要素がコピーまたは複製されます。

実行

このファイルを_clonenode_example_としてサーバーパスに保存します(このファイルとnode.xmlはサーバーの同じパスにある必要があります)。 次のように出力を取得します-

Tanmay Patil, 1234567890, [email protected]
Taniya Mishra, 1234667898, [email protected]
Tanisha Sharma, 1234562350, [email protected]
Tanmay Patil, 1234567890, [email protected]

最初の_Employee_要素が完全に複製されていることがわかります。