Reputation: 41
I am trying to load an XML file using Angular and typescript and then be able to extract some specific node values to use them into calculations and display these in other some component of the app. I am completely new to Angular and typescript (and coding in general). I have done the Angular tutorial but now I am struggling to get started and achieve the objective stated above. I think I need to: - Provide the file path and load the file, and store it in a variable - Convert from XML to something else (JSON?) - Look for a certain "node" based on names and attributes and store value in a variable - Use this variable in the HTML using {{}}.
I tried several options but none worked so far probably because I am mixing different routes.
All I have for now is:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: (.... some html.... that displays title and the image below and the date using {{}} )
export class AppComponent {
title="Welcome !";
Welcome_Image="/Images/Images.JPG";
today=Date.now();
}
Could you please help me get started with the task described above ? Thanks a lot for your help.
Best regards, Laurence
Upvotes: 4
Views: 15477
Reputation: 61
If you wish to convert it XML to JSON, there are a few packages that can help you achieve this. I used the xml2js package. The code looks something link this:
import { promises as fsPromises } from 'fs';
import { parseString } from 'xml2js';
// Declare Variables
let JSONdata = null;
let XMLdata = null;
// Read the XML file
fsPromises.readFile('../xmlParser/test.xml','utf-8')
.then(function(value){
XMLdata = value;
console.log('XML data is: '+ value);
// Parse XML
parseString(XMLdata, function(err, result){
if(err) {
console.log('There was an error when parsing: ' + err);
}
else {
console.log('The JSON version is: ' + JSON.stringify(result));
console.log('The JSON version is: ' + JSON.stringify(result.root.graph)); // Use this format to extract the tags/data you are interested in
JSONdata = result;
// Write the JSON data to a file
fsPromises.writeFile("../xmlParser/edited-test.json", JSON.stringify(JSONdata), 'utf-8')
.then( function() { console.log('Successfully written the file') })
.catch( function(reason) { console.log('Something went wrong when writing the file: '+ reason) });
}
})
})
.catch(function(reason){
console.log('There was some problem reading the file: '+ reason)});
Hope this helps!
Upvotes: 1