SnareChops
SnareChops

Reputation: 13347

Node.js get modified XML into variable for writing

I have been searching all over and I have come up with some good answers, but this last small detail of my task, I have not been able to find a solution.

I have a Node.js implementation that contains the following function. The point of this function is to change some of the settings of an xml file on the server. So far I think I have pretty much everything done, but I can't figure out how to get the processed xml string to write back to the file.

$data is the JSON object from the POST.

function SaveSettings() {
    fs.readFile('config.xml', function (err, data) { //Read the XML file to a string
        if(err) {throw err;}    //If and error, throw error
        var $xml = $(data.toString()).find('settings').each(function () { //Process XML
            $(this).find('background > color').text($data.backgroundColor);
            $(this).find('background > image').text($data.backgroundImage);
            if($data.startupEnabled === "on") {
                $(this).find('startup > enabled').text("true");
            } else {
                $(this).find('startup > enabled').text("false");
            }
            if($data.splashEnabled === "on") {
                $(this).find('startup > splash > enabled').text("true");
            } else {
                $(this).find('startup > splash > enabled').text("false");
            }
            $(this).find('startup > splash > image').text($data.splashImage);
            $(this).find('security > password').text($data.password);
       });

       console.log($xml.toString()); //Contains the output of the jQuery object (Not XML)

        fs.writeFile('config.xml', data.toString(), function (err) {
            if(err) {throw err;}
        }); //data.toString() contains the original XML, unmodified.
    });

    ...
}

I know that this could be done with other languages, but I would really like a Node.js solution. Also I do have the jstoxml module and jquery module loaded in the implementation.

Upvotes: 0

Views: 1099

Answers (1)

You probably want to pass that $data into the functions, not rely on it being global. That said, you can probably get the XML code by doing:

var div = $("<div></div>");
div.append($(this));
var newXMLcode = div.html();

Also note that you're using $(this) all over the place - you probably want to cache that instead, like var $this = $(this) and then using $this instead for all your jQuery-wrapped requirements.

Upvotes: 1

Related Questions