Zeebats
Zeebats

Reputation: 480

jquery problems with xml parsing

I have some problems parsing xml with jquery. I did some research myself, but I didn't find the answer for my problem. The problem is that the parseXml function doesn't show any result in the div with id result and the div information doesn't show "success". When I change qanda.xml to a non exsisting file name like qandaa.xml the information div shows "XML File not found" So I think the file is loaded but something is wrong with the parseXml function.

The 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>

The html page

<!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>

Upvotes: 1

Views: 246

Answers (1)

Paul Grime
Paul Grime

Reputation: 15104

Think your XML needs a root element.

>>> 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]

and

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

Upvotes: 1

Related Questions