I can extract elements from parsed XML like so:
import { XMLParser } from "fast-xml-parser";
let xml = '<gpx myAttr="fred"><trk>track 1</trk><trk>track 2<trkpt>trackpoint 2</trkpt></trk></gpx>';
const options = {
ignoreAttributes: false,
attributeNamePrefix : "@_"
};
const parser = new XMLParser(options);
const root = parser.parse(xml);
const track0 = root.gpx.trk[0]; // gives 'track 1'
const trackpoint = root.gpx.trk[1].trkpt; // gives 'trackpoint 2'
const attr = root.gpx.myAttr; // gives 'undefined'
but trying to get the attribute doesn’t work. Because of the parser’s attributeNamePrefix I have also tried
const attr = root.gpx.@_myAttr;
but of course that gives a syntax error. After I extract an attribute I want to modify it and recreate the XML using XMLBuilder, so I will need something like
root.gpx.myAttr = "newAttr";
There a JSFiddle here.
>Solution :
The code you put into JSFiddle seems mostly correct. However, there is a syntax error in the XML string; the closing tag for <trk> is missing. Here’s the corrected code:
Corrected JSFiddle:
// let xml = '<gpx myAttr="fred"><trk>track 1</trk><trk>track 2<trkpt>trackpoint 2</trkpt></trk></gpx>';
let xml =
'<gpx myAttr="fred"><trk>track 1</trk><trk>track 2</trk><trkpt>trackpoint 2</trkpt></trk></gpx>';
const options = {
ignoreAttributes: false,
attributeNamePrefix: '@_', // you have assign this so use this to access the attribute
};
const parser = new XMLParser(options);
const root = parser.parse(xml);
const track0 = root.gpx.trk[0];
const trackpoint = root.gpx.trk[1].trkpt;
// const attr = root.gpx.myAttr
const attr = root.gpx['@_myAttr']; // Use the correct attribute name
document.getElementById('trk1').innerHTML = track0;
document.getElementById('trk2').innerHTML = trackpoint;
document.getElementById('attr').innerHTML = attr;
Changes made:
- Corrected the missing closing tag for in the xml string.
- Used
root.gpx['@_myAttr']instead ofroot.gpx.myAttrto access the attribute with the correct name.