PDA

View Full Version : Read the XML file using javascript



ponraj
05-24-2014, 07:54 AM
Hi,

i am new to scripting and i would like you ask a help here. i want a javascript to read the following xml and the end result should display

Name = name1
int = 1
ct = 3
Act = 2
Ex = 1
Sum = 1
Ext = 0

the xml content is

<lesson id="52" name = "name1" >
<page id="01" name="int" count="1" />
<page id="02" name="ct" count="3" />
<page id="03" name="Act" count="2"/>
<page id="04" name="Ex" count="1" />
<page id="05" name="Sum" count="1" />
<page id="06" name="Ext" count="0" />
</lesson>

jscheuer1
05-24-2014, 03:13 PM
For this demo, I'm calling the xml file 'lesson.xml'.


<!DOCTYPE html>
<html>
<head>
<title>Read XML - Demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function($){
var $r = $('#result');
$.ajax({
url: 'lesson.xml',
dataType: 'xml',
cache: false,
success: function(data){
var r = [], c;
$('*', data).each(function(i, t){
if((c = t.getAttribute('count'))){
r.push(t.getAttribute('name') + ' = ' + c);
} else {
r.push('Name = ' + t.getAttribute('name'));
}
});
$r.append(r.join('<br>'));
}
});
});
</script>
</head>
<body>
<div id="result"></div>
</body>
</html>