在javascript中获取xml dom子元素

Get xml dom child element in javascript

本文关键字:dom 元素 xml 获取 javascript      更新时间:2023-09-26

我有一个这样的XML文档:

<section>
   <description></description>
   <question>
       <description></description>
   </question>
</section>

我已经将sectionXML存储在一个名为SectionXML的变量中。我使用:

section.description = SectionXML.getElementsByTagName("description")[0].childNodes[0];
section.description = section.description ? section.description.nodeValue : "";

但是,SectionXML.getElementsByTagName("description")返回了许多描述的列表,就好像我们更深入地查看许多孩子(曾孙等)一样,我们可以看到它们都有一个描述,但我只想获取带有"description"标签名称的 SectionXML 的直接子级。我该怎么做?

您可以使用

querySelectorAll():

SectionXML.querySelectorAll("section>description")[0]
// use > to get direct element only