Dom-xml-dom-get-node
XML DOM-ノードの取得
この章では、XML DOMオブジェクトの_node_値を取得する方法について学習します。 XMLドキュメントには、ノードと呼ばれる情報単位の階層があります。 Nodeオブジェクトには、要素の値を返すプロパティ_nodeValue_があります。
次のセクションでは、議論します-
- 要素のノード値を取得する
- ノードの属性値を取得する
次のすべての例で使用される_node.xml_は以下の通りです-
<Company>
<Employee category = "Technical">
<FirstName>Tanmay</FirstName>
<LastName>Patil</LastName>
<ContactNo>1234567890</ContactNo>
<Email>[email protected]</Email>
</Employee>
<Employee category = "Non-Technical">
<FirstName>Taniya</FirstName>
<LastName>Mishra</LastName>
<ContactNo>1234667898</ContactNo>
<Email>[email protected]</Email>
</Employee>
<Employee category = "Management">
<FirstName>Tanisha</FirstName>
<LastName>Sharma</LastName>
<ContactNo>1234562350</ContactNo>
<Email>[email protected]</Email>
</Employee>
</Company>
ノード値を取得
メソッド_getElementsByTagName()_は、指定されたタグ名を持つドキュメント順にすべての_Elements_の_NodeList_を返します。
例
次の例(getnode_example)は、XMLドキュメント(link:/dom/node.xml [node.xml])をXML DOMオブジェクトに解析し、子ノード_Firstname_(0のインデックス)のノード値を抽出します-
<!DOCTYPE html>
<html>
<body>
<script>
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","/dom/node.xml",false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
x = xmlDoc.getElementsByTagName('FirstName')[0]
y = x.childNodes[0];
document.write(y.nodeValue);
</script>
</body>
</html>
実行
このファイルを_getnode_example_としてサーバーパスに保存します(このファイルとnode.xmlはサーバーの同じパスにある必要があります)。 出力では、_Tanmay_としてノード値を取得します。
属性値を取得
属性は、XMLノード要素の一部です。 ノード要素は、複数の一意の属性を持つことができます。 属性は、XMLノード要素に関する詳細情報を提供します。 より正確には、ノード要素のプロパティを定義します。 XML属性は常に名前と値のペアです。 この属性の値は、_attribute node_と呼ばれます。
_getAttribute()_メソッドは、要素名で属性値を取得します。
例
次の例(get_attribute_example)は、XMLドキュメント(link:/dom/node.xml [node.xml])をXML DOMオブジェクトに解析し、カテゴリ_Employee_(index at 2)の属性値を抽出します-
<!DOCTYPE html>
<html>
<body>
<script>
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","/dom/node.xml",false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
x = xmlDoc.getElementsByTagName('Employee')[2];
document.write(x.getAttribute('category'));
</script>
</body>
</html>
実行
このファイルを_get_attribute_example_としてサーバーパスに保存します(このファイルとnode.xmlはサーバーの同じパスにある必要があります)。 出力では、属性値を_Management_として取得します。