Reputation: 9
The question is how to convert xml to json format in angular2? I currently receive the xml from an external page
My service:
import { Injectable } from '@angular/core';
import {Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
@Injectable()
export class Ganado2Service {
private url: string = 'http://bicicardpruebas.itcl.es/prodwservice/api/instalacion'
constructor(private http: Http) { }
getCiudad(id: number) {
return this.http.get(this.url + '/' + id)
.map(response => response.text())
.catch(this.handleError)
.subscribe(data => {
if(data) {
console.log(data);
}
})
}
handleError(error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg);
return Observable.throw(errMsg);
}
}
My component:
export class GanadoComponent implements OnInit {
constructor(private ganadoService: Ganado2Service) { }
ngOnInit() {
this.ganadoService.getCiudad(1).subscribe();
}
}
I do not know what to write inside subscribe.
I want it to return all the xml data.
XML:
<CL_Instalacion xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/ClasesComunes">
<AcquirerBin i:nil="true"/>
<AvisosAltasPimEmailsDestino>[email protected]
</AvisosAltasPimEmailsDestino>
<AvisosAltasWebEmailsDestino i:nil="true"/>
<AvisosEmailOrigen>[email protected]</AvisosEmailOrigen>
<AvisosEmailOrigenEnabledSSL>true</AvisosEmailOrigenEnabledSSL>
<AvisosEmailOrigenHost>smtp.gmail.com</AvisosEmailOrigenHost>
<AvisosEmailOrigenPassword>contrasenafrioindustrial
</AvisosEmailOrigenPassword>
<AvisosEmailOrigenPuerto>587</AvisosEmailOrigenPuerto>
<AvisosIncidenciasEmailsDestino>[email protected],[email protected]
</AvisosIncidenciasEmailsDestino>
<AvisosOcupacionEmailsDestino>[email protected]
</AvisosOcupacionEmailsDestino>
<Ciudad>Burgos</Ciudad>
<ClaveEncriptacion i:nil="true"/>
<HabilitadoHorario>true</HabilitadoHorario>
<Hora>2017-10-27T12:55:51.1868855+02:00</Hora>
<IdiomasPorDefecto>FR</IdiomasPorDefecto>
<MaxBicis>5</MaxBicis>
<id>1</id>
</CL_Instalacion>
How can I do to parse it to json? so I can get the fields I need.
Thanks
Upvotes: 0
Views: 2656
Reputation: 18399
You could parse XML via DOMParser
:
https://www.w3schools.com/xml/xml_parser.asp
Example usage:
var text, parser, xmlDoc;
text = "<bookstore><book>" +
"<title>Everyday Italian</title>" +
"<author>Giada De Laurentiis</author>" +
"<year>2005</year>" +
"</book></bookstore>";
parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");
document.getElementById("demo").innerHTML = xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
Then you would probably need to map that to JS object manually.
Or use some ready made solution, like this:
https://github.com/metatribal/xmlToJSON
https://github.com/abdmob/x2js
Upvotes: 1