XML DOM - 获取节点

在本章中,我们将研究如何获取 XML DOM 对象的 node 值。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() 返回按文档顺序排列且具有给定标签名称的所有 ElementsNodeList

示例

以下示例 (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