2013-04-19 3 views
1

jquery로 xml을 구문 분석하는 데 문제가 있습니다. 나는 약간의 연구를 직접했지만 내 문제에 대한 답을 찾지 못했습니다. 문제는 parseXml 함수가 결과가 div 인 결과를 표시하지 않으며 div 정보가 "success"를 표시하지 않는다는 것입니다. qanda.xml을 qandaa.xml과 같은 존재하지 않는 파일 이름으로 변경하면 정보 영역에 "XML File not found"가 표시되므로 파일이로드되었지만 parseXml 함수에 문제가있는 것 같습니다.xml 구문 분석에 jquery 문제가 있습니다.

는 XML (qanda.xml)

<?xml version="1.0" encoding="UTF-8"?> 
<QandA> 
    <question>how much?</question> 
    <answer>100</answer> 
</QandA>  
<QandA> 
    <question>how much?</question> 
    <answer>110</answer> 
</QandA>  
<QandA> 
    <question>how much?</question> 
    <answer>120</answer> 
</QandA>  
<QandA> 
    <question>how much?</question> 
    <answer>130</answer> 
</QandA>  
<QandA> 
    <question>how much?</question> 
    <answer>140</answer> 
</QandA> 

HTML 페이지

<!DOCTYPE HTML> 
<html> 
<head> 
<LINK REL=StyleSheet HREF="layout.css" TYPE="text/css" MEDIA=screen> 
<script src="http://code.jquery.com/jquery-latest.js"></script> 
<script type="text/javascript"> 
$(document).ready(function() { 

    var information = $("#info"); 
    var result = $("#result"); 

$.ajax({ 
    type: "GET", 
    url: "qanda.xml", 
    datatype: "xml", 
    success: parseXml, 
    error: function(xhr, status, error) { 
     if(xhr.status==404) { 
      information.text("XML file not found"); 
     } 
    } 
}); 

function parseXml(xml) { 
    $(xml).find('QandA').each(function(){ 
     result.append($(this).find('question').text()); 
     result.append($(this).find('answer').text()); 
    }); 
    information.text("Success"); 
} 
}); 
</script> 
</head> 
<body> 

<div id="info"></div> 
<div id="result"></div> 

</body> 
</html> 

답변

1

은 XML 루트 요소를 필요로 생각하십시오.

>>> str = '<?xml version="1.0" encoding="UTF-8"?><root><a></a></root>' 
"<?xml version="1.0" encoding="UTF-8"?><root><a></a></root>" 
>>> $(str).find("a") 
Object[a] 

>>> str = '<?xml version="1.0" encoding="UTF-8"?><a></a>' 
"<?xml version="1.0" encoding="UTF-8"?><a></a>" 
>>> $(str).find("a") 
Object[] 
+0

고맙습니다. 방금 을 XML 문서에 추가하면 제대로 작동합니다. – Zeebats

관련 문제