Encountering difficulty extracting information from an XML document within the Parse Cloud utilizing the XMLReader in an Express application

My goal is to extract elements from an XML file that I have already stored on the Parse Cloud for my Express app. I began coding after finding a helpful resource on using XMLReader with XPath on cloud code, as well as a guide on Parse httpRequest for retrieving Parse files. I conducted a test reading XML elements using XMLReader in the following manner:

exports.xmlmodule = function(req, res) {
if (Parse.User.current()){
Parse.User.current().fetch().then(function(user){
var xmlreader = require('cloud/xmlreader');

var someXml =     '<dataset>'
        +         '<brands>'
        +            '<TheId>1</TheId>'
        +            '<ParentId></ParentId>'
        +            '<CategoryorProductName>Casuals</CategoryorProductName>'
        +         '</brands>'
        +         '<brands>'
        +            '<TheId>34</TheId>'
        +            '<ParentId>1</ParentId>'
        +            '<CategoryorProductName>Jeans</CategoryorProductName>'
        +         '</brands>'
        +    '</dataset>'


xmlreader.read(someXml, function (err, res){
if(err) return console.log(err);

// utilizing the .count() and the .at() functions, you can iterate through nodes with the same name:
for(var i = 0; i < res.dataset.brands.count(); i++){
    console.log( res.dataset.brands.TheId.at(i).text() );
    console.log( res.dataset.brands.ParentId.at(i).text() );
    console.log( res.dataset.brands.CategoryorProductName.at(i).text() );
}

console.log("");


});


});}
else{ res.render('login',{welcome: 'Please login to continue'});}
 };

This approach was successful. (Please disregard the 'user' fetch which is not relevant here).

Next, I attempted to retrieve an XML file from the Parse Cloud using HTTPRequest, which also worked.

However, when I tried merging these two methods to achieve my objective, I encountered an error:

Failed with: TypeError: Object [object Object] has no method 'charAt'
at Object.write (sax.js:918:31)
at Object.exports.read (xmlreader.js:157:12)
at main.js:21:11
at e (Parse.js:2:5101)
at Parse.js:2:4651
at Array.forEach (native)
at Object.x.each.x.forEach [as _arrayEach] (Parse.js:1:665)
at c.extend.resolve (Parse.js:2:4602)
at Object.<anonymous> (<anonymous>:573:17)

I implemented a cloud function, and here is my main.js

require ('cloud/app.js');
var xmlreader = require('cloud/xmlreader');
Parse.initialize("xxxxx", "xxxxx");

Parse.Cloud.define('myxmlfunction',function(req,res){
Parse.User.current().fetch().then(function(user){
var theid= user.get('StoreId');
var Stores= Parse.Object.extend('Stores');
var query= new Parse.Query(Stores);
query.equalTo('objectId', theid);
query.first().then(function(results){
var xmlfile= results.get('xmlfile');
Parse.Cloud.httpRequest({
url: xmlfile.url()
}).then(function(thefile){

var file = new Parse.File('thexml.xml', {
 base64: thefile.buffer.toString("base64")
});

xmlreader.read(file, function (err, res){
if(err) return console.log(err);

// using the .count() and the .at() function, you can loop through nodes with the same name:
 for(var i = 0; i < res.myrecord.brands.count(); i++){
     console.log( res.myrecord.brands.TheId.at(i).text() );
      console.log( res.myrecord.brands.ParentId.at(i).text() );
     console.log( res.myrecord.brands.CategoryorProductName.at(i).text() );
 }

 console.log("");

 });

 file.save().then(function() {
 res.success();
 }, function(error) {
 res.error(error);
 });
  });
  });
  });
  });

Note: the error indicated in log main.js 21:11 points to "xmlreader.read". It seems that the XML file being retrieved from the cloud cannot be processed by XMLReader.

Here is a snippet of my XML file:

 <?xml version="1.0" encoding="UTF-8"?>
 <myrecord>
    <brands>
       <TheId>a</TheId>
       <PId > g</PId>          
       <CategoryNameorProductName >Martin</CategoryNameorProductName>
    </brands>
    <brands>
       <TheId>b</TheId>
       <PId > c</PId>           
       <CategoryNameorProductName >Levis</CategoryNameorProductName>
    </brands> 
</myrecord>

The error mentions 'charAt'. I am relatively new to coding, having started just a month ago and reviewing W3 XML tutorials earlier today. Any assistance would be greatly appreciated!

Answer №1

Issue resolved! Initially, there was a typo in the XML file where "PId" needed to be replaced with "ParentId". Additionally, the error related to the question was pointed out by @timothy - the result of the httpRequest method can be found in 'thefile' and the actual file is located in 'thefile.buffer'. To read the XML data using xmlreader input, it's recommended to use thefile.buffer.toString(). Furthermore, a mistake was identified in the looping function within main.js as I mistakenly misplaced the .at() method. Below is the final code for retrieving an XML file from Parse Cloud and extracting its node elements using xmlreader:

require ('cloud/app.js');
var xmlreader = require('cloud/xmlreader');
Parse.initialize("xxxx", "xxxx");

Parse.Cloud.define('myxmlfunction',function(req,res){
Parse.User.current().fetch().then(function(user){
var theid= user.get('StoreId');
var Stores= Parse.Object.extend('Stores');
var query= new Parse.Query(Stores);
query.equalTo('objectId', theid);
query.first().then(function(results){
var xmlfile= results.get('xmlfile');
Parse.Cloud.httpRequest({
url: xmlfile.url()
}).then(function(thefile){

xmlreader.read(thefile.buffer.toString(), function (err, res){
if(err) return console.log(err);

// Looping through nodes with the same name using .count() and .at():
 for(var i = 0; i < res.myrecord.brands.count(); i++){
    console.log( res.myrecord.brands.at(i).TheId.text() );
    console.log( res.myrecord.brands.at(i).ParentId.text() );
    console.log( res.myrecord.brands.at(i).CategoryNameorProductName.text() );
}

console.log("");

});


}).then(function() {
res.success();
}, function(error) {
res.error(error);
 });
});
});
});

The XML file content:

<?xml version="1.0" encoding="UTF-8"?>
<myrecord>
    <brands>
       <TheId>a</TheId>
       <ParentId > g</ParentId>          
       <CategoryNameorProductName >Martin</CategoryNameorProductName>
    </brands>
    <brands>
       <TheId>b</TheId>
       <ParentID > c</ParentID>           
       <CategoryNameorProductName >Levis</CategoryNameorProductName>
    </brands> 
</myrecord>

Log result:

Input: {}
Result: undefined
I2014-07-29T05:56:42.879Z] Levis
I2014-07-29T05:56:42.880Z]  c
I2014-07-29T05:56:42.881Z] a
I2014-07-29T05:56:42.881Z] b
I2014-07-29T05:56:42.881Z] Martin
I2014-07-29T05:56:42.884Z] 
I2014-07-29T05:56:42.885Z]  g

I'll definitely be more vigilant about typos going forward.

Answer №2

As opposed to the actual string required by the XmlReader, you are providing your Parse.File instance (file) as input.

Instead, utilize the content of your thefile variable which contains the actual file data.

Remember, the Parse.File class is designed for saving files to the cloud and storing a reference to them in a class.

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

Is it possible in MongoDB to search for an exact data match using the && condition?

I've implemented a sign-in form and stored user information in MongoDB Atlas https://www.mongodb.com/cloud/atlas/. Here is an example of how my data is structured: _id:60a64bee48f6eed16a566cf5 user_name:"test1" user_password:&qu ...

How can I incorporate a fade opacity effect into my Div scrolling feature?

I successfully implemented code to make div elements stick at the top with a 64px offset when scrolling. Now, I am trying to also make the opacity of these divs fade to 0 as they scroll. I am struggling to figure out how to achieve this effect. Below is ...

Preventing the mysql server called by php from running when the website is refreshed

My local website runs by querying a mysql database using inputs from an html form. The form values are passed to php via jQuery to execute the query. Is there a way to send a command to the mysql server to terminate the query if the web page is refreshed? ...

The zip() operator in RxJS is not functioning as intended. It consistently finishes execution without emitting any values

Suppose you have an observable containing a large number of elements, say 450 or more. You want to transfer these elements to a different observable in batches of 100 elements each. You can check out a functional example provided by @martin at this link: ...

Exploring Angular unit testing using Jasmine: Techniques to customize or delete spyOn

Current software versions for AngularJS and Jasmine: AngularJS v1.2.26 Jasmine v2.2.0 I am facing an issue with a spyOn. When attempting to change or remove its behavior, I encounter the following error message: Error: getUpdate has already been spied u ...

The Node.js application is unable to locate the source file path

Currently, I am in the process of creating a simple quiz application. While working on this project, I encountered an issue with linking a JS file in an HTML template. Even though I have confirmed that the path is correct, every time I run my node app, the ...

What is the method for retrieving a specific value following the submission of an AngularJS form?

Here is how my form begins: <!-- form --> <form ng-submit="form.submit()" class="form-horizontal" role="form" style="margin-top: 15px;"> <div class="form-group"> <label for="inputUrl" class="col-sm- ...

Implementing Typescript for managing state in React components

Currently, I have a state set up like this: const [newInvoice, setInvoice] = useState<InvoiceType | null>(invoice) The structure of my InvoiceType is as follows: customer_email: string customer_name: string description: string due_date: stri ...

Discover the pixel width of a Bootstrap grid row or container using JavaScript

How can I calculate the width of a Bootstrap grid row or container in pixels using JavaScript? I am working with Aurelia for my JavaScript project, but I'm open to solutions in standard JS (no jQuery, please). Looking at the Bootstrap documentation, ...

Show only specific items in an AngularJS application

As a newcomer to AngularJS and the Ionic framework, I'm currently working with the basic Starter Tabs Ionic template. I would like to implement a "Favourite/Bookmark" feature for certain items and display them on a separate tab. The structure of my b ...

Update the state within a forEach iteration

Is there a way to update state when clicking on buttons? I keep getting an error. Error: Uncaught TypeError: this.setState is not a function I understand that this.setState cannot be used here, but I'm unsure of where to bind it. class Popup extend ...

Step-by-step guide to performing an AJAX request in JavaScript while using Ubuntu

My current setup involves using a JavaScript file in conjunction with NodeJS to execute AJAX calls. To accomplish this, I have installed and imported jQuery as demonstrated below: var http = require("http"); $ = require("jquery"); test(); funct ...

Tips for creating a custom Angular Material modal window that is fully responsive to its parent modal window

Hey there! I've put together a custom modal window in Angular Material by combining the custom modal window example with the Angular Material slider demo. Everything is working well except for the fact that the sliders inside the modal window are not ...

Enhancing 2D video viewing with Threejs interactivity

I want to create an interactive 2D video using three.js and maintain the aspect ratio of the video when resizing the browser window. Here is the code I am currently using: var camera, scene, renderer; var texture_placeholder, distance = 500; init() ...

Navigating through the directories in PUG using the absolute path

Referring to the docs for PUG (), it states: If a path is absolute (example: include /root.pug), it gets resolved by prepending options.basedir. Otherwise, paths are resolved in relation to the file being compiled. To clarify, I understand that this in ...

NodeJs - Uncaught Typeerror: Cannot create an instance of Post

Currently, I am developing a blog application using NodeJs. I encountered an issue when trying to save posts in the database. The error message that appeared after submitting the form is as follows: TypeError: Post is not a constructor index.html <fo ...

The process of enzyme shallow rendering involves the rendering of child components

Currently, I am attempting to shallow render a component in order to conduct some elementary unit tests. This particular component contains two child components that are rendered multiple times based on the parent's props. Upon querying the shallowl ...

How do I determine whether an object is a Map Iterator using JavaScript?

I'm working on some NodeJS code that involves a Map Iterator object. How can I accurately determine if a Javascript object is a "Map Iterator"? Here are the methods I have attempted: typeof myMap.keys() returns 'Object' typeof myMap.keys() ...

When the form is submitted, the values of the items are being reverted back

I'm currently working on a single web page using nodejs, expressjs, and mongoDB. On the page, I have two text boxes that define the filter clause for the collection in mongoDB. Additionally, there is an HTML table that displays the documents from the ...

Angular application navigation does not work as expected when the application is served in Express.js

I have an Angular 7 application that is running on an ExpressJS server. This is how the server part of the app is set up: app.get('/', (req, res) => { console.log(`sending...`); res.sendFile(path.join(__dirname, 'index.html') ...