Error: Angular does not recognize x2js XML format

I'm attempting to adapt this particular example to utilize xml as json data. However, I am encountering some issues with the code.

courses  = x2js.xml_str2json(data);
console.log(courses.books.course);
$scope.todos = courses.books.course;

In the XML of the example, there are 'books' and 'course' tags. But I am unsure where 'courses' is coming from.

I am trying to replicate this example using the following 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>

Here is my HTML snippet:

X = x2js.xml_str2json(data);
console.log(X.DocumentElement.semt_kodlari);
$scope.todos = X.DocumentElement.semt_kodlari;

Upon running this code, I encounter a "Cannot read property 'semt_kodlari' of undefined" error. Could someone please point out what may be wrong in my code and clarify the distinction between 'course' and 'course's'?

Answer №1

It seems that you are just missing one parent element for your object. Try adding diffgram to your console.log and everything should function as intended.

For a demonstration, please refer to the example below or visit it on 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 = '<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);
            }
        });
<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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Typescript to test with Karma, we can inject a service for our

I'm currently experiencing a problem with running tests in my application. I recently transitioned to using TypeScript and am still in the learning process. The specific error I'm encountering is: Error: [$injector:unpr] Unknown provider: movie ...

Having trouble removing just one element from an array in Redux. Any suggestions on how to make it work properly?

I'm currently working on creating a dynamic algorithm for removing an item from an array. Reducer: import { LOAD_PAGES, REMOVE_PAGE } from "./dynamicMenuActions"; export const initialState = { pages: [] }; export const dynamicMenuReducer = (state ...

Develop an array in JavaScript using PHP on the server side

I have successfully created a JavaScript array in PHP and sent it to the client. However, I am now wondering how to create a JavaScript array with PHP and store it on the server. Can anyone provide some guidance on this? Thanks in advance! ...

Installing material-ui using npm does not always result in getting the most up-to-date version

I'm currently facing a dilemma with an abandoned project that serves as the admin tool for my current project. The Material-UI version used in this project is 0.19.4. However, when I remove the dependency from my package.json file and execute npm inst ...

Tips for transitioning from GWT to AngularJS

Since the development plugin has been discontinued, GWT development feels less enjoyable. Each small modification results in long recompilations and debugging a mix of Java and Javascript in the browser. I'm considering transitioning to AngularJS. Ca ...

What is the best way to display HTML content inside a pop-over window?

How can I load popover content from another HTML file using templateUrl in AngularJS? Check out the demo below: HTML: <!DOCTYPE html> <html ng-app="plunker"> <head> <meta charset="utf-8"/> <title>AngularJS Plunker& ...

Combining the powers of $.get and $.ready

Basically, I am facing an issue with my ajax call where sometimes it completes before the page is fully loaded. I attempted to use $( fn ) to wrap the callback function, but unfortunately, the callback does not trigger if the page is already loaded. Does a ...

What is the best way to retrieve the second to last element in a list

When using Protractor, you have convenient methods like .first() and .last() on the ElementArrayFinder: var elements = element.all(by.css(".myclass")); elements.last(); elements.first(); But what about retrieving the element that comes right before the ...

Puppeteer causes Express to stop listening to incoming requests

As I work on developing a straightforward API that utilizes Puppeteer to execute actions, I encounter an issue where my Express app stops listening once Puppeteer is launched. Below is the script in question: const Apify = require('apify'); cons ...

Intellisense with JavaScript methods is not supported in Vue files

While running Vue 2.6 in VSCode, I've noticed that my intellisense functions perfectly within js files. However, as soon as I switch to a vue file, all my intellisense capabilities disappear. I have the most up-to-date version of VSCode installed and ...

I am encountering difficulties with a nodejs query where I am unable to successfully include the "+" symbol as part of the query

Every time I submit a query for B+ or A+ {{URL}}/api/help/?bloodType=B+ it ends up showing as empty space, like this. Is there a way to properly pass the "+" sign in the query? Thanks. P.S: _ works fine. {"bloodType":"B "} ...

What is the method to retrieve the class name of an element when the div is created as '<div id 'one' class="element one"></div>'?

I have three elements named one, two, and three, declared as seen below: <div id =container> <div id 'one' class="element one"></div> <div id 'two' class="element two"></div> < ...

Error message: Invalid credentials for Twitter API authentication

My attempts to post a tweet seem to be failing for some reason. I suspect that the issue might be related to the signature string, but from following Twitter's instructions on signing requests, everything appears correct. Here is the code snippet I ...

Cannot display GIF file from the SRC directory in a React application

I am trying to display a gif from the "/src/images" folder in my component, but I keep getting my "old" value displayed instead. What could be causing this issue? Snippet from Danke.js site: import Confetti from "../images/confetti.gif"; <Box sx={{ ju ...

Ensure that the user's credentials are accessible to all views in Node.js

I'm currently developing an Android application that utilizes Node.js web services. The initial interface requires the user to connect to a host using an IP address, login, and password in order to access all databases. I aim to save these credentials ...

Accessing a property's value from a different property within a Class' initialization function

I encountered a challenge while trying to access the value returned in one method within a property of another method belonging to a different constructor. The specific error message I received was "TypeError: Cannot read property 'name' of undef ...

Implementing event listeners with Angular UI-Router

Currently, I am working with Angular 1.4.5 and Angular Ui Router. I am facing an issue where I am trying to utilize addEventListener to execute a function when a text field is blurred. The challenge I am encountering is that during the load state, the elem ...

Swap out the HTML button element for text once the form is submitted

On the main page, I have a button that opens a modal when clicked. Inside the modal, there is a form with a submit button that closes the modal and returns to the main page. After closing the modal, I want to change the HTML button on the main page to plai ...

"Implementing a comment system using Node.js and MySQL: A comprehensive guide

Hey there! I have some data that I want to use to create a hierarchical data example. { id_commentForum: 1, id_user: 1, id_thread: 1, comment: 'This is the First Comment', parent: 0, created_at: Wed Jun 22 2016 13:36:38 G ...

Trouble with image click event in jQuery/JavaScript

I am having trouble with my HTML and JS code. I have added images to my HTML page and want to make it so that when the image is clicked, an alert box pops up. However, for some reason, my JavaScript isn't working as expected. Here is a snippet of my ...