在javascript中需要有关Xpath方法的帮助(selectSingleNode,selectNodes)

时间:2010-06-02 09:39:26

标签: javascript xpath

我想优化我的javascript但是我遇到了一些麻烦。我正在使用XSLT转换,其基本思想是获取XML的一部分并将其子查询,以便调用更快,更便宜。这是XML的一部分:

<suite>
<table id="spis" runat="client">
    <rows>                      
        <row id="spis_1">               
        <dispatch>'2008', '288627'</dispatch>       
        <data col="urGod">
            <title>2008</title>
            <description>Ur. god.</description>
        </data>
        <data col="rbr">
             <title>288627</title>
             <description>Rbr.</description>
        </data>

...

    </rows>
</table>
</suite>

在页面中,这是适用于此的javascript:

// this is my global variable for getting the elements so I just get the most
// I can in one call    

elemCollection = iDom3.Table.all["spis"].XML.DOM.selectNodes("/suite/table/rows/row").context;

//then I have the method that uses this by getting the subresults from elemCollection
//rest of the method isn't interesting, only the selectNodes call

_buildResults = function (){
        var _RowList = elemCollection.selectNodes("/data[@col = 'urGod']/title");
        var tmpResult = [''];
        var substringResult="";
        for (i=0; i<_RowList.length; i++) {
            tmpResult.push(_RowList[i].text,iDom3.Global.Delimiter);
        }
...


//this variant works

elemCollection = iDom3.Table.all["spis"].XML.DOM

_buildResults = function (){
        var _RowList = elemCollection.selectNodes("/suite/table/rows/row/data[@col = 'urGod']/title");
        var tmpResult = [''];
        var substringResult="";
        for (i=0; i<_RowList.length; i++) {
            tmpResult.push(_RowList[i].text,iDom3.Global.Delimiter);
        }

...

问题是,我找不到使用子结果来获得我需要的方法。

2 个答案:

答案 0 :(得分:2)

您正尝试从集合中选择节点(NodeList)。

elemCollection.selectNodes("/data[@col = 'urGod']/title");

尝试从集合中选择单个项目(Node)中的节点,例如:

elemCollection[i].selectSingleNode("/data[@col = 'urGod']/title")

添加到您的代码中(没有数据验证,并假设我们想要col属性的第一个匹配项):

_buildResults = function (){
        var tmpResult = [''];
        var substringResult="";
        for (i=0; i<elemCollection.length; i++) {
            tmpResult.push(elemCollection[i].selectSingleNode("/data[@col = 'urGod']/title").text,iDom3.Global.Delimiter);
        }

答案 1 :(得分:1)

您需要迭代elemCollection列表,然后执行以下查询:

./data[@col = 'urGod']/title