Dom-xml-dom-set-node
XML DOM-セットノード
この章では、XML DOMオブジェクトのノードの値を変更する方法について学習します。 ノード値は次のように変更できます-
var value = node.nodeValue;
_node_が_Attribute_の場合、_value_変数は属性の値になります。 _node_が_Text_ノードの場合、テキストコンテンツになります。 _node_が_Element_の場合、_null_になります。
以下のセクションでは、各ノードタイプ(属性、テキストノード、および要素)のノード値設定を示します。
次のすべての例で使用される_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>
テキストノードの値を変更
Node要素の変更値を言うとき、要素(_text node_とも呼ばれます)のテキストコンテンツを編集することを意味します。 次の例は、要素のテキストノードを変更する方法を示しています。
例
次の例(set_text_node_example)は、XMLドキュメント(link:/dom/node.xml [node.xml])をXML DOMオブジェクトに解析し、要素のテキストノードの値を変更します。 この場合、各_Employee_の_Email_を[email protected]_に送信し、値を出力します。
<!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("Email");
for(i = 0;i<x.length;i++) {
x[i].childNodes[0].nodeValue = "[email protected]";
document.write(i+');
document.write(x[i].childNodes[0].nodeValue);
document.write('<br>');
}
</script>
</body>
</html>
実行
このファイルを_set_text_node_example_としてサーバーパスに保存します(このファイルとlink:/dom/node.xml [node.xml]はサーバーの同じパスにある必要があります)。 次の出力が表示されます-
0) [email protected]
1) [email protected]
2) [email protected]
属性ノードの値を変更
次の例は、要素の属性ノードを変更する方法を示しています。
例
次の例(set_attribute_example)は、XMLドキュメント(link:/dom/node.xml [node.xml])をXML DOMオブジェクトに解析し、要素の属性ノードの値を変更します。 この場合、各_Employee_の_Category_をそれぞれ_admin-0、admin-1、admin-2_に設定し、値を出力します。
<!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");
for(i = 0 ;i<x.length;i++){
newcategory = x[i].getAttributeNode('category');
newcategory.nodeValue = "admin-"+i;
document.write(i+');
document.write(x[i].getAttributeNode('category').nodeValue);
document.write('<br>');
}
</script>
</body>
</html>
実行
このファイルを_set_node_attribute_example_としてサーバーパスに保存します(このファイルとlink:/dom/node.xml [node.xml]はサーバーの同じパスにある必要があります)。 結果は次のようになります-
0) admin-0
1) admin-1
2) admin-2