我试着让this example使用xml作为json数据。但我对这些代码存在一些问题。
courses = x2js.xml_str2json(data);
console.log(courses.books.course);
$scope.todos =courses.books.course;
在xml的例子中。有书和课程标签。但我不明白“课程”来自哪里。
我试着用这个xml示例
做同样的例子<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
<DocumentElement xmlns="">
<semt_kodlari diffgr:id="semt_kodlari1" msdata:rowOrder="0">
<semt_adi>ALTIKAT</semt_adi>
</semt_kodlari>
</DocumentElement>
</diffgr:diffgram>
这是我的HTML部分:
X = x2js.xml_str2json(data);
console.log(X.DocumentElement.semt_kodlari);
$scope.todos = X.DocumentElement.semt_kodlari;
当我运行此代码时,我采取了“无法读取属性'semt_kodlari'未定义”错误。那么有人可以告诉我我的代码有什么问题吗?关于课程和课程的不同之处是什么?
答案 0 :(得分:1)
我认为你只缺少对象的一个父级。如果您向diffgram
添加console.log
,则应该按预期工作。
请参阅下面的演示或jsfiddle。
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.factory('getXMLDataFactory', function() {
var x2js = new X2JS(),
//xml ="<MyRoot><test>Success</test><test2><item>val1</item><item>val2</item></test2></MyRoot>";
xml = '<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">'+
'<DocumentElement xmlns="">'+
'<semt_kodlari diffgr:id="semt_kodlari1" msdata:rowOrder="0">'+
'<semt_adi>ALTIKAT</semt_adi>'+
'</semt_kodlari>'+
'</DocumentElement>'+
'</diffgr:diffgram>';
console.log(xml, x2js);
return {
get: function() {
return x2js.xml_str2json(xml);
}
};
});
todoApp.controller('todosCtrl', function ($scope, todoFactory, getXMLDataFactory) {
$scope.todos = [];
//loadTodos();
loadData();
function loadTodos() {
todoFactory.getTodos().success(function (data) {
console.log(data);
courses = x2js.xml_str2json(data);
console.log(courses.books.course);
$scope.todos = courses.books.course;
});
}
function loadData() {
console.log('test');
$scope.todos = getXMLDataFactory.get()
.diffgram.DocumentElement.semt_kodlari;
console.log($scope.todos);
}
});
&#13;
<script src="http://demos.amitavroy.com/learningci/assets/js/xml2json.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="todosApp" ng-controller="todosCtrl">
<h2>Parsing XML data with AngularJS</h2>
{{todos|json}}
</div>
&#13;