2013-05-14 68 views
0

XML值我有這樣的XML訪問使用jQuery

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
<soapenv:Body> 
<sizeResponse soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> 
<sizeReturn xsi:type="xsd:int">1</sizeReturn> 
</sizeResponse> 
</soapenv:Body> 
</soapenv:Envelope> 

我想訪問1,但.find()不工作它給了我在我的控制檯此錯誤

Uncaught TypeError: Object <?xml version="1.0" 
encoding="UTF-8"?><soapenv:Envelope 
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><sizeResponse 
soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><sizeReturn 
xsi:type="xsd:int">0</sizeReturn></sizeResponse></soapenv:Body></soapenv:Envelope> 
has no method 'getElementsByTagName' 

如何我可以使用jQuery或JS訪問它嗎(如果有一種使用Xpath插件的方式,請提供Xpath表達式)?

謝謝

+0

我認爲這可以幫助你:[https://github.com/doedje/jquery.soap](https://github.com/doedje/jquery.soap) – vher2 2013-05-14 05:38:28

+1

那不值得downvote – Ben 2013-05-14 07:43:54

回答

1

試試這個:

var xml = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><sizeResponse soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><sizeReturn xsi:type="xsd:int">0</sizeReturn></sizeResponse></soapenv:Body></soapenv:Envelope>', 
xmlDoc = $.parseXML(xml), 
$xml = $(xmlDoc); 
console.log($xml.find("sizeReturn").html()); 

閱讀文檔http://api.jquery.com/jQuery.parseXML/

小提琴:http://jsfiddle.net/cY5xZ/

+0

沒有工作抱歉的人;看看是否有幫助我在Ajax調用的數據變量中有XML字符串 – 2013-05-14 05:38:49

+0

@查看知識:也許你應該在你的問題中給出更多的上下文(例如,不工作的JavaScript部分。) – 2013-05-14 06:42:44

1

你可以試試這個。

<script> 
    function GetVal() 
    { 
     var txt = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><sizeResponse soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><sizeReturn xsi:type="xsd:int">0</sizeReturn></sizeResponse></soapenv:Body></soapenv:Envelope>'; 
     if (window.DOMParser) 
     { 
      parser=new DOMParser(); 

      xmlDoc = parser.parseFromString(txt, "text/xml"); 

      var v = xmlDoc.getElementsByTagName("sizeReturn")[0].childNodes[0].nodeValue; 
      alert("t" +v); 
     } 
     else // Internet Explorer 
     { 
      xmlDoc=new ActiveXObject("Microsoft.XMLDOM"); 
      xmlDoc.async=false; 
      xmlDoc.loadXML(txt); 
     } 
    } 

</script> 

乾杯:)