Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to extract an attribute using xml-fast-parser

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

  1. Corrected the missing closing tag for in the xml string.
  2. Used root.gpx['@_myAttr'] instead of root.gpx.myAttr to access the attribute with the correct name.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading