- XML DOM 基礎
- XML DOM - 首頁
- XML DOM - 概述
- XML DOM - 模型
- XML DOM - 節點
- XML DOM - 節點樹
- XML DOM - 方法
- XML DOM - 載入
- XML DOM - 遍歷
- XML DOM - 導航
- XML DOM - 訪問
- XML DOM 操作
- XML DOM - 獲取節點
- XML DOM - 設定節點
- XML DOM - 建立節點
- XML DOM - 新增節點
- XML DOM - 替換節點
- XML DOM - 刪除節點
- XML DOM - 克隆節點
- XML DOM 物件
- DOM - 節點物件
- DOM - NodeList 物件
- DOM - NamedNodeMap 物件
- DOM - DOMImplementation
- DOM - DocumentType 物件
- DOM - ProcessingInstruction
- DOM - 實體物件
- DOM - 實體引用物件
- DOM - 符號物件
- DOM - 元素物件
- DOM - 屬性物件
- DOM - CDATASection 物件
- DOM - 註釋物件
- DOM - XMLHttpRequest 物件
- DOM - DOMException 物件
- XML DOM 有用資源
- XML DOM - 快速指南
- XML DOM - 有用資源
- XML DOM - 討論
XML DOM - 獲取節點
本章將學習如何獲取XML DOM物件的節點值。XML文件具有稱為節點的資訊單元層次結構。節點物件具有屬性nodeValue,它返回元素的值。
在以下部分中,我們將討論:
獲取元素的節點值
獲取節點的屬性值
以下所有示例中使用的node.xml如下:
<Company>
<Employee category = "Technical">
<FirstName>Tanmay</FirstName>
<LastName>Patil</LastName>
<ContactNo>1234567890</ContactNo>
<Email>tanmaypatil@xyz.com</Email>
</Employee>
<Employee category = "Non-Technical">
<FirstName>Taniya</FirstName>
<LastName>Mishra</LastName>
<ContactNo>1234667898</ContactNo>
<Email>taniyamishra@xyz.com</Email>
</Employee>
<Employee category = "Management">
<FirstName>Tanisha</FirstName>
<LastName>Sharma</LastName>
<ContactNo>1234562350</ContactNo>
<Email>tanishasharma@xyz.com</Email>
</Employee>
</Company>
獲取節點值
getElementsByTagName()方法返回文件中所有具有給定標籤名稱的元素的NodeList,按文件順序排列。
示例
以下示例 (getnode_example.htm) 將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.htm(此檔案和node.xml應位於伺服器上的同一路徑)。輸出結果中,我們得到節點值為Tanmay。
獲取屬性值
屬性是XML節點元素的一部分。節點元素可以具有多個唯一的屬性。屬性提供有關XML節點元素的更多資訊。更準確地說,它們定義了節點元素的屬性。XML屬性始終是名稱-值對。屬性的值稱為屬性節點。
getAttribute()方法透過元素名稱檢索屬性值。
示例
以下示例 (get_attribute_example.htm) 將XML文件 (node.xml) 解析為XML DOM物件,並提取類別Employee (索引為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.htm(此檔案和node.xml應位於伺服器上的同一路徑)。輸出結果中,我們得到屬性值為Management。
廣告