I'm currently working with xml2js. I'm trying to parse a xml file with the following structure:
<?xml version='1.0' encoding='UTF-8'?>
<document>
<teachers>
<teacher>
<id>1</id>
<first_name>Gawen</first_name>
<last_name>Rosenstengel</last_name>
<email>grosenstengel0@google.com.hk</email>
</teacher>
<teacher>
<id>2</id>
<first_name>Fabien</first_name>
<last_name>Stanford</last_name>
<email>fstanford1@usa.gov</email>
</teacher>
</teachers>
<ships>
<ship>
<id>1</id>
<name>Brazelton</name>
<length>218</length>
<crew>555</crew>
</ship>
<ship>
<id>2</id>
<name>Ailsbury</name>
<length>121</length>
<crew>197</crew>
</ship>
</ships>
</document>
I use the following async method (Typescript) to parse it:
async parseXMLFile(path: string): Promise<any | undefined> {
let xmlString = await fs.readFile(path, "latin1");
let result = await xml2js.parseStringPromise(xmlString, xmlParseOptions);
return result;
}
The options I use are the following:
export const xmlParseOptions = {
explicitArray: false,
mergeAttrs: true,
explicitRoot: false
};
The output that results from the parsing:
{
teachers: {
teacher: [
{ id: '1', first_name: 'Gawen', last_name: 'Rosenstengel', email: 'grosenstengel0@google.com.hk' },
{ id: '2', first_name: 'Fabien', last_name: 'Stanford', email: 'fstanford1@usa.gov' }
]
},
ships: {
ship: [
{ id: '1', name: 'Brazelton', length: '218', crew: '555' },
{ id: '2', name: 'Ailsbury', length: '121', crew: '197' }
]
}
}
My question now is with which settings I can achieve the following format:
{
teachers: [
{ id: '1', first_name: 'Gawen', last_name: 'Rosenstengel', email: 'grosenstengel0@google.com.hk' },
{ id: '2', first_name: 'Fabien', last_name: 'Stanford', email: 'fstanford1@usa.gov' }
],
ships: [
{ id: '1', name: 'Brazelton', length: '218', crew: '555' },
{ id: '2', name: 'Ailsbury', length: '121', crew: '197' }
]
}
Im relatively new to xml so maybe I'm doing something wrong. I already thank you for your answers in advance :)