2011-08-24 82 views
0

我试图在Javascript中分析一个xml文件,而忽略了xml文件的命名空间。我预计未来xml文件的命名空间会发生变化,但如果代码能够工作,即使命名空间确实发生了任意变化,我也会感到更高兴。我试图按照these instructions失败。在Firefox中使用XPath命名空间

我需要更改什么,以便我的第二个版本成功找到xml节点?下面是我的代码,不能按预期工作。具体而言,第三次致电Components.utils.reportError输出null)。

的Javascript(在Firefox扩展):

Components.utils.reportError("XML A: " + docky.documentElement); 
var testxpath = '//' + docky.documentElement.tagName + ":entry"; 
Components.utils.reportError("Test XPath: " + testxpath); 
Components.utils.reportError(docky.evaluate(testxpath, docky, 
    function(){return 'http://tempuri.org/';}, 
    XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue); 

XML文件:

<OutputBlob xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
     xmlns="http://tempuri.org/"> 
    <rnd> 
     <double>0.23500252665719135</double> 
     <double>0.82559380951597994</double> 
     <double>0.33431208335529644</double> 
     <double>0.91389494431852125</double> 
    </rnd> 
</OutputBlob> 

输出:

XML A: [object Element] 
Test XPath: //OutputBlob:entry 
null 

下面找到我的代码的变化(即,不涉及名称空间)作为e xpected。也就是说,拨打Components.utils.reportError的第三个电话不会输出null

的Javascript(在Firefox扩展):

Components.utils.reportError("XML A: " + docky.documentElement); 
var testxpath = '//' + docky.documentElement.tagName; 
Components.utils.reportError("Test XPath: " + testxpath); 
Components.utils.reportError(docky.evaluate(testxpath, docky, null, 
    XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue); 

XML文件:

<OutputBlob xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:xsd="http://www.w3.org/2001/XMLSchema" > 
    <rnd> 
     <double>0.23500252665719135</double> 
     <double>0.82559380951597994</double> 
     <double>0.33431208335529644</double> 
     <double>0.91389494431852125</double> 
    </rnd> 
</OutputBlob> 

输出:

XML A: [object Element] 
Test XPath: //OutputBlob 
[object Element] 

回答

0

修复:更换

var testxpath = '//' + docky.documentElement.tagName + ":entry"; 

var testxpath = '//entry:' + docky.documentElement.tagName;