Search code examples
javascriptangulartypescriptangular7

is there any possible to read each node from xml


I am using Angular 7.

<note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <Employees>
    <Employee>
    <Name>nameOne</Name>
    <Id>IdOne</Id>
    </Employee>
    <Employee>
    <Employee-Name>empName</Employee-Name>
    </Employee>
    <Employee>
    <Employee-Id>IdEmp</Employee-Id>
    </Employee>
    </Employees>
</note>
  • Clients are uploading different .XML files and each file must have but parent node may different in uploaded files..

  • need read each node and compare have or not, if yes then we will use that id

  • my code

const parser = new xml2js.Parser({ strict: false, trim: true });
parser.parseString(uploadedXMLData, (err, result) => {
    const obj: any[] = result;
    console.log(result);
    Object.entries(obj).forEach((data, index) => {
        console.log('Data::: ', data, index);
        data[0]['NOTE'].forEach((empData, indexNumber) => {
            console.log('Emp Data::: ', empData, indexNumber);
        });
    });
});
  • But with this code able to get particular node value like empData.Employee[1].EmployeeName[1].Employee-Name
  • How to print each node
  • thanks in advance

Solution

  • To reach each node, despite the structure of the XML you need to use recursion, like here:

    function printNode(xml, key?) {
        if (xml == null) {
            console.log(`Node is empty`);
            return;
        }
    
        if (Array.isArray(xml)) {
            return xml.forEach((v) => printNode(v, key));
        }
    
        if (typeof xml === 'object') {
            return Object.entries(xml).forEach(([key, v]) => printNode(v, key));
        }
    
        console.log(`${key}:${xml}`);
    }