2011-11-29 3 views
5

jQuery를 사용하여 xml 응답을 구문 분석하고 페이지의 요소 만 출력하려고하지만이 경우에는 실패합니다.jQuery를 사용하여 XML 응답을 구문 분석하는 방법

다음은 응답 구문에 &을 구문 분석하는 데 사용하는 코드입니다.

$.ajax({ 
    url: UCMDBServiceUrl, 
    type: "POST", 
    dataType: "xml", 
    data: soapMessage, 
    success: UCMDBData, 
    crossDomain: true, 
    contentType: "text/xml; charset=\"utf-8\"" 
}); 
alert("Sent2"); 
return false; 
} 

function UCMDBData(xmlHttpRequest, status, msg) 
{ 
    alert("Came back1"); 
    $(xmlHttpRequest.responseXML).find('tns:CIs').each(function() 
    { 
     alert("Came back2"); 
     $(this).find("ns0:CI").each(function() 
     { 
      alert("Came back3"); 
      $("#output").append($(this).find("ns0:ID").text()); 
     }); 
    });  
} 

"Came back1"에 대한 경고를 받고 있지만 더 이상 진행되지 않는 것으로 보입니다. 아래는 위의 jquery 코드를 사용하여 구문 분석하려는 XML 응답입니다. 내가 궁극적으로 응답에서 반환하려고 텍스트는 그래서 제 질문은 어떻게 제대로 데이터를 구문 분석 할 것을이 요소

<?xml version='1.0' encoding='utf-8'?> 
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Header /> 
    <soapenv:Body> 
     <tns:getFilteredCIsByTypeResponse xmlns:ns0="http://schemas.hp.com/ucmdb/1/types" xmlns:ns1="http://schemas.hp.com/ucmdb/ui/1/types" xmlns:ns2="http://schemas.hp.com/ucmdb/1/types/query" xmlns:ns3="http://schemas.hp.com/ucmdb/1/types/props" xmlns:ns4="http://schemas.hp.com/ucmdb/1/types/classmodel" xmlns:ns5="http://schemas.hp.com/ucmdb/1/types/impact" xmlns:ns6="http://schemas.hp.com/ucmdb/1/types/update" xmlns:ns7="http://schemas.hp.com/ucmdb/discovery/1/types" xmlns:ns8="http://schemas.hp.com/ucmdb/1/types/history" xmlns:tns="http://schemas.hp.com/ucmdb/1/params/query"> 
      <tns:CIs> 
       <ns0:CI> 
        <ns0:ID>4d030502995a00afd989d3aeca2c990c</ns0:ID> 
        <ns0:type>nt</ns0:type> 
        <ns0:props> 
         <ns0:strProps> 
          <ns0:strProp> 
           <ns0:name>name</ns0:name> 
           <ns0:value>prodoo</ns0:value> 
          </ns0:strProp> 
         </ns0:strProps> 
         <ns0:booleanProps> 
          <ns0:booleanProp> 
           <ns0:name>host_iscomplete</ns0:name> 
           <ns0:value>false</ns0:value> 
          </ns0:booleanProp> 
         </ns0:booleanProps> 
        </ns0:props> 
       </ns0:CI> 
      </tns:CIs> 
      <tns:chunkInfo> 
       <ns0:numberOfChunks>0</ns0:numberOfChunks> 
       <ns0:chunksKey> 
        <ns0:key1 /> 
        <ns0:key2 /> 
       </ns0:chunksKey> 
      </tns:chunkInfo> 
     </tns:getFilteredCIsByTypeResponse> 
    </soapenv:Body> 
</soapenv:Envelope> 

에? 나는 코드 구문이 정확하다고 믿지만 예상 된 결과를 얻지는 못한다. 고마워. 고마워. "나는 단지 경고 메시지를 실행하면

$.ajax({ 
    url: UCMDBServiceUrl, 
    type: "POST", 
    dataType: "xml", 
    data: soapMessage, 
    success: UCMDBData, 
    crossDomain: true, 
    contentType: "text/xml;" 
    }); 
alert("Sent2"); 
return false; 
} 

function UCMDBData(data, textStatus, jqXHR) { 
    alert("Came back1"); 
    $(data).find('tns:CIs').each(function() { 
     alert("Came back2"); 
     $(this).find("ns0:CI").each(function() { 
      alert("Came back3"); 
      $("#output").append($(this).find("ns0:ID").text()); 
      document.AppServerForm.outputtext.value = document.AppServerForm.outputtext.value + "http://localhost:8080/ucmdb/cms/directAppletLogin.do?objectId=" + $(this).find('ns0:ID').text() +"&infopane=VISIBLE&navigation=true&cmd=ShowRelatedCIs&interfaceVersion=8.0.0&ApplicationMode=ITU&customerID=1&userName=admin&userPassword=admin"; 

    }); 
}); 

}

내가는 다시받을 수 없습니다 :

편집

는 내가 제안처럼 다음에 내 코드를 수정,하지만 여전히 운이 Came back1 "은 코드가 여전히 jquery로 xml을 제대로 통과하지 못한다는 것을 의미합니다. 다른 제안?

+0

ns0 : CI의 단일 인스턴스와 일치 시키려고합니까 아니면 두 번 이상 나타날 수 있습니까? – JesseBuesking

+0

여기에 게시 된 XML 응답에서 알 수 있듯이 ns0 : CI의 단일 인스턴스 만 반환됩니다. – user1013396

답변

2

네임 스페이스 범위의 이름을 약간 다르게 처리해야 할 것이다. 이 대답에 따르면 : jQuery XML parsing with namespaces 대신 속성 선택자 [@ nodeName = tns : CIs]를 사용해야합니다.

jQuery 버전 1.3 이상인 경우 "@"을 삭제해야 할 수 있습니다. 또 다른 제안은 .find ('tns \ : CIs') 콜론에서 벗어나는 것입니다. 구문 상 접두사를 의미 적 네임 스페이스 (uri)와 겹치기 때문에 해킹이 될 수 있습니다. 따라서 접두사가 변경되면이 방법은 중단됩니다. 더 정확한 답은 접두사와 네임 스페이스 URI의 매핑을 인식합니다. jquery-xmlns plugin for namespace-aware selectors은 그 점에서 유망 해 보입니다.

+0

이것이 효과적입니다! 정말 고마워! – user1013396

+0

사실 나는 여전히 문제가 있습니다. Firefox에서 작동하지만 Internet Explorer 8에서는 작동하지 않습니다 (여기서 사용되는 것은 무엇입니까). – user1013396

+1

JQuery에서 버그라고 말할 수있는 근처 : http://bugs.jquery.com/ticket/155 – jerseyboy

1

jQuery 성공 함수의 형식이 잘못되었습니다. 그것은 당신의 $.ajax 기능에, 형태 또한

function UCMDBData(data, textStatus, jqXHR) { 
    alert("Came back1"); 
    $(data).find('tns:CIs').each(function() { 
     alert("Came back2"); 
     $(this).find("ns0:CI").each(function() { 
      alert("Came back3"); 
      $("#output").append($(this).find("ns0:ID").text()); 
     }); 
    }); 
} 

될 필요가 대신 당신이 (당신이 서버에 XML을 보내는 가정) 전에 무슨의 contentType: "text/xml"가되도록 contentType 라인을 변경합니다.

자세한 내용은 jQuery.ajax() documentation을 참조하십시오.

+0

찾기가 네임 스페이스에서 작동하지 않습니다. – Christophe

0

아마 올바른 구문은

success: function(xml) { 
    $(xml).find('tns:CIs').each(function() { 
    ...... 
+0

jQuery 1.7에서 작동하지 않습니다. – Christophe

1

귀하의 의견을 바탕으로, jQuery에 열중 한 이유는 무엇입니까? 그냥 자바 스크립트 자체를 사용하십시오!

var open = '<ns0:ID>'; 
var close = '</ns0:ID>'; 

var start = obj.indexOf(open) + open.length; 
var end = obj.indexOf(close); 

var result = obj.slice(start, end); 

여기에 작동중인 모습을 보여주는 jsfiddle이 있습니다.

+1

이 예제에서는 작동하지만 노드에 특성이 있으면 중단됩니다. – Christophe

관련 문제