Motyar

@motyar

Freelance Web Developer

Static Web Hosting, made easy

Aug 4, 2014

How to parse XML in Angular JS

Still many webServices and REST APIs provide output in XML, AngularJS doent work with XML data.

We are going to use x2js, to convert XML data to JSON object. All other code will not be effected any way.

We are going to parse this XML sample file
<?xml version="1.0" encoding="ISO-8859-1"?>
<books>
<course number="1">
<name>First course</name>
<page>1</page>
</course>
<course number="2">
<name>Getting started</name>
<page>2</page>
</course>
</books>
view raw out.xml hosted with ❤ by GitHub
Here is very basic example code.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<script type="text/javascript" src="https://raw.githubusercontent.com/abdmob/x2js/master/xml2json.min.js" charset="UTF-8"></script>
<meta charset="utf-8">
<title>Parsing XML in ajgularJS</title>
</head>
<body ng-app="todosApp">
<h2>Parsing XML data with AngularJS</h2>
<input type="text" ng-model="search" class="search-query" placeholder="Search">
<div ng-controller="todos"><ol><li ng-repeat="todo in todos | filter:search">{{todo.name}}</div>
<script>
var todoApp = angular.module('todosApp',[]);
todoApp.factory('todoFactory',function($http){
var factory = [];
factory.getTodos = function(){
return $http.get("http://cdn.rawgit.com/motyar/bcf1d2b36e8777fd77d6/raw/bfa8bc0d2d7990fdb910927815a40b572c0c1078/out.xml");
}
return factory;
});
todoApp.controller('todos',function($scope,todoFactory){
$scope.todos = [];
loadTodos();
function loadTodos(){
var x2js = new X2JS();
todoFactory.getTodos().success(function(data){
courses = x2js.xml_str2json(data);
console.log(courses.books.course);
$scope.todos =courses.books.course;
});
}
});
</script>
</body>
</html>
view raw angularxml.html hosted with ❤ by GitHub

Labels: , , ,




By :