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

廣告
© . All rights reserved.