Generating XML format from JSON using JavaScript

I am looking to create an XML format based on my JSON data, rather than converting it from JSON to XML.

Here is an example of the JSON I want to convert to XML:

var jsonData = { "Smart Shoes":{  
      "Product":"Smart Shoes",
      "Price":24.99,
      "Quantity":"1x "
   },
   "Denim Jeans":{  
      "Product":"Denim Jeans",
      "Price":30,
      "Quantity":"1x "
   }
}

I aim to generate XML in a similar format as shown below:

<xml id="POSCMD" LateProcessing="true">
 <commands>
  <injectfieldmacro type="field" name="FIELD_CLEAR"/>
    forEach(Item in Basket) {
      <injectdata type="literal" data="{Item.UPC}"/>
      <injectfieldmacro type="field" name="FIELD_UPC"/>
    }
  </commands>
</xml>

Plnkr link for reference

Answer №1

Utilizing JavaScript (or jQuery) allows you to dynamically create XML elements in a DOM-style approach, which is considered superior to constructing a string due to its ability to manage proper format and encapsulation.

Below is an example using JavaScript:

var jObj = { "Smart Shoes":{  
      "Product":"Smart Shoes",
      "Price":24.99,
      "Quantity":"1x "
   },
   "Denim Jeans":{  
      "Product":"Denim Jeans",
      "Price":30,
      "Quantity":"1x "
   }
};

var xml = document.createElement("xml");
xml.setAttribute("id","POSCMD");
xml.setAttribute("LateProcessing","true");
var commands = document.createElement("commands");
xml.appendChild(commands);
var injFM = document.createElement("injectfieldmacro");
injFM.setAttribute("type","field");
injFM.setAttribute("name","FIELD_CLEAR");
commands.appendChild(injFM);
var injData;
for (var item in jObj) {
    injData = document.createElement("injectdata");
    injData.setAttribute("type","literal");
    injData.setAttribute("data",JSON.stringify(jObj[item]));
    injFM = document.createElement("injectfieldmacro");
    injFM.setAttribute("type","field");
    injFM.setAttribute("name","FIELD_UPC");
    commands.appendChild(injData);
    commands.appendChild(injFM);
}

// Append XML to DOM
var body = document.getElementsByTagName("body")[0];
body.appendChild(xml);

The code provided inserts the JSON object data into the data field, as it was not explicitly outlined how this process should be carried out. Nevertheless, the snippet above offers enough guidance to allow for further customization, particularly if there is a requirement to separate the data into distinct "injectdata" XML elements.

Edit: The snippet has been updated so that the XML element is directly added to the DOM body tag. Upon running the script, inspecting the iframe after right clicking should reveal these elements embedded within the DOM:

https://i.sstatic.net/4N834.png

Answer №2

Quick and straightforward.

var generateXML = function() {
    var itemsObj = {"Smart Watch":{"Product":"Smart Watch","Price":99.99,"Quantity":"1x "},"Bluetooth Speaker":{"Product":"Bluetooth Speaker","Price":49.99,"Quantity":"2x "}};

    var xmlString = '<xml id="INVENTORYCMD" LateProcessing="true"><commands><injectfieldmacro type="field" name="FIELD_CLEAR"/>';

    for (var item in itemsObj) {
      if (itemsObj.hasOwnProperty(item)) {
        xmlString += '<injectdata type="literal" data="' + itemsObj[item].Price + '"/>'; 
        xmlString += '<injectfieldmacro type="field" name="FIELD_CODE"/>';
      }
    }

    xmlString += '</commands></xml>';

    console.log(xmlString);
}

The output will be a correctly formatted XML like this:

<?xml version="1.0" encoding="UTF-8"?>
<xml id="INVENTORYCMD" LateProcessing="true">
   <commands>
      <injectfieldmacro type="field" name="FIELD_CLEAR" />
      <injectdata type="literal" data="99.99" />
      <injectfieldmacro type="field" name="FIELD_CODE" />
      <injectdata type="literal" data="49.99" />
      <injectfieldmacro type="field" name="FIELD_CODE" />
   </commands>
</xml>

I recommend converting your objects/arrays to XML format.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The implementation of pushing inside a foreach loop is not correctly adding elements to

I have encountered an issue with running a foreach loop and adding values to an array in my code. The first foreach loop works as expected, adding values properly to the array. However, the second foreach loop seems to be malfunctioning as none of its valu ...

Ways to display Multiple Images in a Listview

I am facing an issue where multiple images are displayed inside a List View Item perfectly, but after scrolling the page, duplicate images appear within the list view item. I am dynamically creating ImageView and adding it to a Linear Layout. How can I fix ...

Enhance the editing capabilities of the Json data form

https://i.stack.imgur.com/YZIjb.png My goal is to enhance a form for editing json data by moving beyond the typical <textarea /> tag and making it more user-friendly. Are there any tools available that can help improve the form's usability? Add ...

I'm encountering difficulty accessing the Index value within the template's Ref

I'm having trouble accessing the index value inside the templateRef. It shows as undefined in the console. <ng-container *ngFor="let notification of notifications; let i = index"> <ng-template *ngTemplateOutlet="notificationPage ...

Encountering a Forbidden Error with Superagent

Here is the content of my index.js file I am attempting to fetch a response from a sports data API. I can successfully send curl requests to it, but when trying this method, I encounter a 403 forbidden error. var express = require('express'); v ...

Issues with sending FormData through Ajax POST requests over a secure HTTPS connection

We are currently experiencing issues with uploading pictures to our server. The process works smoothly on http sites, but encounters errors on https sites. An error message is displayed:https://i.sstatic.net/hPMZv.png Failed to load resource: the server r ...

Do you think there is a more efficient way to solve this issue?

const [active, setActive] = React.useState(["active", "", "", "", ""]);``your unique text`` const hrefs = React.useMemo( () => ["/", "/about", "/skills", "/projects", "/contact"], [] ); React.useEffect(() => { setInterval(() => { ...

Is IPv6 like a JavaScript string in any way?

Introduction In the era of IPv4, life was simpler as IPv4 addresses could easily be converted into 32-bit integers for various calculations. However, with the introduction of IPv6, things have become more complicated due to the lack of native support for ...

Scene three js appears to be stuck in a perpetual state of emptiness, making it challenging to start

I've encountered a major issue with understanding how to use three.js. Despite my best efforts over the past few days, I haven't been able to successfully implement three.js into my projects. Initially, I attempted using Parcel by starting a new ...

Testing the number of times module functions are called using Jest

As someone who is relatively new to JavaScript and Jest, I am faced with a particular challenge in my testing. jest.mock('./db' , ()=>{ saveProduct: (product)=>{ //someLogic return }, updateProduct: (product)=>{ ...

Tips for utilizing a variable from a function in one file within a function in another file

Having trouble using the variable counter from one function in a different file? In the first function, I defined counter without using "var" thinking it would make it a global variable. But for some reason, it doesn't seem to work. Help needed! //fun ...

Angular, JavaScript, and PHP are three powerful programming languages that

This file contains HTML code <ul class="list"> <li id="numword" data-score="{{item.score}}" class="" ng-repeat="item in words track by $index"> {{item.word}} {{item.score}} </li> </ul> Here is the visual representa ...

Online application for saving a vast quantity of information on the user's device

Is there a way for a web application to store an extensive amount of data client-side, allowing for millions of records to be accessed offline by users exclusively on Chrome? I initially considered indexedDb, but I discovered it becomes almost unusable wi ...

Uploading image files using Node Express and returning them as JSON in an API response

Is it possible to send json along with an image file in Express? I know that you can serve an image using res.sendFile const path = require('path'); app.get('/image/:filename', (req, res, next) => { res.type('png'); r ...

Testing the updated version 18 of Create React APP index.js using Jest

Previously, I had this index.js file created for React version <= 17. import React from 'react'; import ReactDOM from 'react-dom'; import App from './views/App'; import reportWebVitals from './reportWebVitals'; im ...

Creating an API service using URL queries with the capability to display 20 data items per page, utilizing the CodeIgniter PHP framework

Creating an API service for my images directory is the goal, with specific features in mind: The ability to use a URL query to display 20 image URLs per page. Reverse sorting functionality. For example: Existing images stored in the directory: /i ...

When you hover over them, Material UI icons shrink in size due to the Border

I've been working on a React application that includes Material UI icons in the header. My goal is to add a border at the bottom of each icon when hovered over, but currently, the borders are too close to the icons. Another problem I'm facing is ...

Automated login feature in JQuery utilizing localStorage

I've been working on implementing an automatic login feature for users using the "Remember Me" functionality. Below is the code I have written, but unfortunately, it's not logging in users automatically: if (localStorage.getItem("username") != ...

Angular II slash avoiding Pipe

I am working on developing a customized pipe in Angular 2 that will handle the replacement of the backslash ('\') character in a given string. This backslash is commonly used to escape special characters. What I have accomplished so far: T ...

Ways to determine if the user is either closing the browser or navigating to a different website

I am looking to set up session management in a manner where all sessions are expired or destroyed when the user closes the browser or tab. However, I would like to retain all the sessions if the user is navigating to another website. Is there a way to ac ...