如何在JavaScript中处理嵌套的XML结构?

时间:2021-09-09 13:09:13

I have the following nested XML structure

我有以下嵌套的XML结构

<forum>
   <title>Title1</title>
   <id>123</id>
   <forum>
       <title>Title1b</title>
       <id>123b</id>
   </forum>
</forum>
<forum>
   <title>Title2</title>
   <id>321</id>
</forum>
<forum>
   <title>Title3</title>
   <id>456</id>
</forum>

As you can see in the above structure, I have a nested "forum" tag in the first element but not in the second and third. I have tried running a if getElementsByTagName("forum").item(0).text on the parent nodes, but it throws an error for the second and third parent nodes because the child node for "forum" doesn't actually exist.

正如您在上面的结构中看到的,我在第一个元素中有一个嵌套的“论坛”标记,但在第二个和第三个元素中没有。我试过运行if getElementsByTagName(“论坛”).item(0)。父节点上的文本,但是它会为第二个和第三个父节点抛出错误,因为“forum”的子节点实际上并不存在。

How could I properly check to see if those child nodes exist and then act on them?

如何正确地检查这些子节点是否存在,然后对它们进行操作?

Thanks!!!

谢谢! ! !

1 个解决方案

#1


0  

You didn't use the innerText method nor did you identify the parent element. Also, getElementsByTagName returns an array. My example works as expected.

您没有使用innerText方法,也没有标识父元素。另外,getElementsByTagName返回一个数组。我的例子和预期的一样。

http://jsfiddle.net/M2F64/2/

http://jsfiddle.net/M2F64/2/

#1


0  

You didn't use the innerText method nor did you identify the parent element. Also, getElementsByTagName returns an array. My example works as expected.

您没有使用innerText方法,也没有标识父元素。另外,getElementsByTagName返回一个数组。我的例子和预期的一样。

http://jsfiddle.net/M2F64/2/

http://jsfiddle.net/M2F64/2/