IE9 NOT getting 'children' of XML node

IE9 NOT getting 'children' of XML node

本文关键字:XML node of children IE9 NOT getting      更新时间:2023-09-26

我在javascript中有一个名为RoomPriceInfo的变量:

<?xml version="1.0" encoding="UTF-8"?>
<BkgItemHotelRoomPrices CurrCode="EUR">
  <RoomType Code="DB" Count="1" Desc="Double" Age="0">
    <PriceInfo EndDate="2011-12-17" AgentMarkup="0.0" MarkupPerc="0.1075" FitRdg="0.25"  MarkupPrice="48.73" AgentPrice="48.75" StartDate="2011-12-11" Nights="7" FitRdgPrice="48.75" CurrDec="2" CurrDecPrice="48.75" SuppPrice="44.0"/>
  </RoomType>
</BkgItemHotelRoomPrices>

和以下代码:

DBRoomPrice = RoomPriceInfo.doXPath("//RoomType[@Code='DB']");
alert(DBRoomPrice[0].children.length);

在Ubuntu的FF7和WinXP的FF8下,我得到1的警报,这是正确的。然而,在WinXP的IE8和Windows 7的IE9下,什么都不会发生。它只是静静地死去。

有人能解释一下吗?如果我在DOM对象上做一个getElementById然后请求它的子对象,那么IE8 &

Internet Explorer(包括版本11!)不支持XML元素的.children属性。

如果您想获得子元素的数量,使用element.childElementCount (IE9+):

element.children.length;   // Does not work in IE on XML elements
element.childElementCount; // Works in every browser

如果您只想知道一个元素是否有任何子元素,您还可以检查element.firstElementChild(或element.lastElementChild)是否不为空。在IE9+中支持此属性:

element.children.length === 0;      // All real browsers
element.firstElementChild !== null; // IE 9+

如果要遍历XML节点的所有子元素,请使用childNodes并通过nodeType:

排除非元素节点。
for (var i = 0, len = element.childNodes.length; i < l; ++i) {
    var child = element.childNodes[i];
    if (child.nodeType !== 1/*Node.ELEMENT_NODE*/) continue;
    // Now, do whatever you want with the child element.
}

这可能解决不了问题,但是…您应该使用childNodes而不是children属性来访问子节点。我不确定哪一个更好,但我知道肯定childNodes是广泛支持的。也许微软也是这样做的?!