XML DOM獲取節點

在本章中,將學習如何獲取XML DOM對象的節點值。 XML文檔具有稱為節點的資訊單元的層次結構。 Node對象有一個屬性 - nodeValue,它返回元素的值。

在以下部分中,將討論學習 -

  • 獲取元素的節點值
  • 獲取節點的屬性值

以下所有示例中使用的node.xml如下所示 -

<Company>
   <Employee category = "Technical" id = "firstelement">
      <FirstName>Susen</FirstName>
      <LastName>Su</LastName>
      <ContactNo>1584567890</ContactNo>
      <Email>susen@xuhuhu.com</Email>
   </Employee>

   <Employee category = "Non-Technical">
      <FirstName>Max</FirstName>
      <LastName>Su</LastName>
      <ContactNo>1334667898</ContactNo>
      <Email>maxsu@xuhuhu.com</Email>
   </Employee>

   <Employee category = "Management">
      <FirstName>Min</FirstName>
      <LastName>Su</LastName>
      <ContactNo>1364562350</ContactNo>
      <Email>minsu@xuhuhu.com</Email>
   </Employee>
</Company>

1. 獲取節點值

使用getElementsByTagName()方法以文檔順序返回具有給定標記名稱的所有元素的NodeList

示例
以下示例(getnode example.html)將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","/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.html 並放在伺服器WEB目錄中(此檔和node.xml應位於伺服器中的同一路徑上)。 在輸出中得到節點值為:Susen ,如下圖所示 -

2. 獲取屬性值

屬性是XML節點元素的一部分。 節點元素可以具有多個唯一屬性。 屬性提供有關XML節點元素的更多資訊。 更確切地說,它們定義節點元素的屬性。 XML屬性始終是名稱-值對。 屬性的值稱為屬性節點。

getAttribute()方法按元素名稱檢索屬性值。

示例

以下示例(get_attribute.html )將XML文檔(node.xml)解析為XML DOM對象,並提取Employee中的category屬性的值(索引是2) -

<!DOCTYPE html>
<html>
   <body>
      <script>
         if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
         } else {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
         }
         xmlhttp.open("GET","/node.xml",false);
         xmlhttp.send();
         xmlDoc = xmlhttp.responseXML;

         x = xmlDoc.getElementsByTagName('Employee')[2];
         document.write(x.getAttribute('category'));
      </script>
   </body>
</html>

執行

將此檔保存為:getnode_example.html 並放在伺服器WEB目錄中(此檔和node.xml應位於伺服器中的同一路徑上)。 在輸出中得到節點屬性值為:Management ,如下圖所示 -


上一篇: XML DOM訪問 下一篇: XML DOM設置節點