0

How to convert dynamically created JSON object to XML in node.js ?

I have to dynamically create JSON object based on available which contains nested list of objects.

var Obj = {
      root: {
        Door_Keeper: {
          ID: {
            '#list': [{
              Key: {
                Name: "Door_Keeper_ID",
                Value: DoorKeeper.dkId
              }
            }, {
              Key: {
                Key_Name: "ID",
                Key_Value: DoorKeeper.id.Id
              }
            }]
          },
          Name: doorKeeper.dkName,
          Description: doorKeeper.dkId,
          Settings: dkSettings,
          '#list':
          //Here I have list of objects which will be added dynamically

        }
      }
    };

I want to generate XML string from the above JSON object in node.js

4
  • 1
    What do you want this XML to look like? There is no direct correlation between JSON and XML. Commented Jun 22, 2015 at 23:35
  • Hi. I am using mongoDB to fetch the data. It gives me list of objects which needs to be converted in tags. Commented Jun 23, 2015 at 16:03
  • <root> <Door_Keeper> <ID> <Key> <Name>Door_Keeper_ID</Name> <Value>rahul</Value> </Key> <Key> <Key_Name>KL12</Key_Name> <Key_Value>DEV-KL12</Key_Value> </Key> </ID> <Name>ABC</Name> <Description>abc ltd</Description> <Settings> xyz </Settings> <shits> </shifts> </Door_Keeper> </root> My result should look like this. In this case for shifts I am getting list of objects which needs to be iterated and converted to XML. Commented Jun 23, 2015 at 16:12
  • Have you found the solution? You can try fast-xml-parser Commented Feb 17, 2018 at 3:57

1 Answer 1

1

Use the npm library, js2xml and it will be like,

var Js2Xml = require("js2xml").Js2Xml;
var obj = ...... //as given by you in the question
var js2xml = new Js2Xml("root", obj);
js2xml.toString();
Sign up to request clarification or add additional context in comments.

2 Comments

Hi. I got this but I am stuck at creating this var obj. It contains list of objects. How should I iterate that inside this obj. Once I am able to generate obj then I can pass it to library for conversion.
For example in ID I have list of keys. I know that its gonna be 2 so I have defined it statically. What If I don't know how many keys will come from DB. How to define it in my var obj .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.