Reputation: 3570
I am making a call to the Google Map API and get a response which seems like basic XML.
Attempting to Parse the XML using DOMParser is failing, with some sort of parsing error, but I don't understand why.
The entire code:
let result: ILatitudeLongitude = { latitude: 0, longitude: 0 };
let axiosConfig = {
headers: { 'Accept': 'application/xhtml+xml' }
};
let url = 'http://some-server/api/GoogleMaps/GetGoogleAPI?fullAddress=123 some st, suburb, state, 1000';
let response = await axios.get(url, this.axiosConfig);
if (response && response.data) {
let parser = new DOMParser();
// response.data looks like this: "<lat>-34.9441798</lat><lng>138.5997218</lng>"
let xmlDoc = parser.parseFromString(response.data, "application/xhtml+xml");
if (xmlDoc) {
try {
let lng = xmlDoc.getElementsByTagName('lng')[0].childNodes[1].nodeValue;
let lat = xmlDoc.getElementsByTagName('lat')[0].childNodes[1].nodeValue;
if (lat && lng) {
result.latitude = +lat;
result.latitude = +lng;
}
} catch (e) {
errorHandler.handle(e);
}
}
}
return result;
Attempting to retrieve the 'lng' element just fails:
xmlDoc.getElementsByTagName('lng')
=> 0 results
If I inspect the elements of the xmlDoc via this statement:
xmlDoc.querySelectorAll('*')
I see that it parses the 'lat' element, but then it gives me a parsererror element. Digging into the parsererror element, I find:
"error on line 1 at column 61: Extra content at the end of the document"
Which is confusing because the XML string doesn't even have 61 characters...its 46 characters in length.
Any ideas on how I could successfully parse this little snippet of XML?
Upvotes: 0
Views: 572
Reputation: 241768
An XML document must have exactly one root element, there can't be two elements at the top level: XML Specification.
Upvotes: 3