IE9没有得到XML节点的“孩子”

时间:2011-11-21 10:19:10

标签: javascript xml internet-explorer internet-explorer-9 children

我在javascript中将以下XML放在名为RoomPriceInfo的var中:

<?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&amp; IE9表现正常。

2 个答案:

答案 0 :(得分:14)

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

如果您想获得子元素的数量,请使用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.
}

答案 1 :(得分:0)

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

相关问题