jsonnode.jsxmlnpm

Convert XML to JSON with NodeJS


I'm trying to convert the following xml to json, thereby I need to get a mapping to the TS-tc-dt

Here is the xml

<?xml version="1.0" encoding="UTF-8"?>
<TestScenario>
   <TestSuite name="TS_EdgeHome">
      <TestCaseName name="tc_Login">dt_EdgeCaseHome,dt_EdgeCaseRoute</TestCaseName>
      <TestCaseName name="tc_Logout">dt_EdgeCaseRoute</TestCaseName>
   </TestSuite>
   <TestSuite name="TS_EdgePanel">
      <TestCaseName name="tc_AddContract">dt_EdgeCaseHome,dt_EdgeCaseSpectrum</TestCaseName>
   </TestSuite>
      <TestSuite name="TS_EdgeRoute">
      <TestCaseName name="tc_VerifyContract">dt_EdgeCaseRoute</TestCaseName>
      <TestCaseName name="tc_Payment">dt_EdgeCaseRoute</TestCaseName>
   </TestSuite>
   <TestSuite name="TS_EdgeSpectrum">
      <TestCaseName name="tc_ClientFeedback">dt_EdgeCaseSpectrum</TestCaseName>
   </TestSuite>
</TestScenario>

How can I achieve this in NodeJS?


Solution

  • You can use xml2json npm for converting your xml in to json. xml2json.

    Step 1:- Install package in you project

    npm install xml2json

    Step 2:- You can use that package and convert your xml to json

    let xmlParser = require('xml2json');
    let xmlString = `<?xml version="1.0" encoding="UTF-8"?>
    <TestScenario>
       <TestSuite name="TS_EdgeHome">
          <TestCaseName name="tc_Login">dt_EdgeCaseHome,dt_EdgeCaseRoute</TestCaseName>
          <TestCaseName name="tc_Logout">dt_EdgeCaseRoute</TestCaseName>
       </TestSuite>
       <TestSuite name="TS_EdgePanel">
          <TestCaseName name="tc_AddContract">dt_EdgeCaseHome,dt_EdgeCaseSpectrum</TestCaseName>
       </TestSuite>
          <TestSuite name="TS_EdgeRoute">
          <TestCaseName name="tc_VerifyContract">dt_EdgeCaseRoute</TestCaseName>
          <TestCaseName name="tc_Payment">dt_EdgeCaseRoute</TestCaseName>
       </TestSuite>
       <TestSuite name="TS_EdgeSpectrum">
          <TestCaseName name="tc_ClientFeedback">dt_EdgeCaseSpectrum</TestCaseName>
       </TestSuite>
    </TestScenario>`;
    
    console.log('JSON output', xmlParser.toJson(xmlString));
    

    Hope this might be helps to you.