1

How can I add new node/element or update xml file in node js express? I try to do it with cheerio, my code:

$ = cheerio.load("my.xml", {xmlMode: true});    
$('urlset').append('<url><loc>www.google.com</loc></url>');
3
  • Can you just format the whole XML file into JSON, and then add the data you want, and once is done, just format the JSONback to XML? Commented Aug 8, 2017 at 14:37
  • Hi, thanks for you answer, if you have some example how to convert xml to json it will help me, thanks Commented Aug 9, 2017 at 21:29
  • I posted the answer below, I hope that will help you Commented Aug 10, 2017 at 3:40

1 Answer 1

2

You just format the whole XML file into JSON, and then add the data you want, and once is done, just format the JSON to XML

const js2xmlparser = require('js2xmlparser');
const xml2js = require('xml2js').parseString;

// Rading your XML file
const origin  = '<?xml version="1.0" encoding="UTF-8"?> <root> <name>Felix</name> </root>';
// Making a JSON object so you can edit it easily
xml2js(origin, (error, editableJSON) => {
    if(error){
        console.log(error);
    }else{
        editableJSON.stackOverflow = true;
        // Making it back to XML
        const resultXML = js2xmlparser.parse('root', editableJSON);
        console.log(resultXML)
    }
});

Demo https://runkit.com/moongod101/598bd24d5a737100125cb948

Sign up to request clarification or add additional context in comments.

Comments

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.