【问题标题】:Display nodes in JavaScript在 JavaScript 中显示节点
【发布时间】:2011-07-28 14:06:21
【问题描述】:

我需要遍历一个 XML 文档并显示满足特定条件的节点。我能够通过 http 获取文件并从中获取满足条件的节点。但我无法在屏幕上显示它们,也看不到它们。

我尝试了所有不同的方法,但都是徒劳的,

XML 结构:

<routeElement>
 <Service>
  <name>RetrieveEmployeeDetailV001</name>
 </Service>
 <Service>
  <name>RetrieveEmployeeAccountDetailV001</name>
 </Service>
</routeElement>

这是我卡在的一段代码......

xmlDocument.setProperty("SelectionLanguage", "XPath");
finalData=xmlDocument.selectNodes("//service");

我使用了不同的方式来访问 finalData 的子节点。

finalData[0].childNodes[0].nodeValue;
finalData.childNodes[0].nodeValue; 
finalData[0].getElementByTagName("service");
finalData[0].firstChild

等等等等。但是什么都没有解决。你能提出一个解决问题的方法吗?

【问题讨论】:

  • 你在使用任何 javascript 框架吗?以下答案中提供的链接适用于 .NET4.0 组件,它不是 javascript。我想知道您是否尝试自己做太多的底层工作,而您可能会使用一些东西来抽象出很多浏览器的不一致性。

标签: javascript xml nodes


【解决方案1】:

如果要选择带有javascript/xpath的节点,可以使用document.evaluate。比如:

var xresult = document.evaluate('//service',xmlDocument, null, 
                          XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null),
              result,
              ret = [];
while (result = xresult.iterateNext()) {
   ret.push(result);
};
//=> the `ret`-array should contain the nodes you searched

这适用于大多数浏览器,IE 除外。对于 IE 使用SelectNodes

另外,我认为常规 DOM 方法应该可以工作,在这种情况下,xmlDocument.getElementsByTagName('service') 将返回 NodeList

【讨论】:

  • 您好,感谢您的 cmets。我使用的是 IE,所以我使用了 selectNodes。
猜你喜欢
  • 2016-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多