XML DOM - 获取节点

在本章中,我们将研究如何获取XML DOM对象的 node 值. XML文档具有称为节点的信息单元的层次结构. Node对象有一个属性 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","https://img01.yuandaxia.cn/Content/img/tutorials/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 (此file和node.xml应位于服务器的同一路径上).在输出中,我们得到节点值为 Tanmay .

获取属性值

属性是XML的一部分节点元素.节点元素可以具有多个唯一属性. Attribute提供了有关XML节点元素的更多信息.更确切地说,它们定义节点元素的属性. XML属性始终是名称 - 值对.该属性值称为属性节点.

getAttribute()方法按元素名称检索属性值./p>

示例

以下示例(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","https://img01.yuandaxia.cn/Content/img/tutorials/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 (此file和node.xml应位于服务器的同一路径上).在输出中,我们将属性值作为 Management .