2

How can I edit XML file by xml2js

const fs = require('fs');
const xml2js = require('xml2js');
var fn = 'file.xml';
fs.readFile(fn, function(err, data) {
   parser.parseString(data, function(err, result) {
       //result.data[3].removeChild(); ?????
       //result.date[2].name.innerText = 'Raya'; ?????
   });
});

This is not working!

Ashish Patil
  • 1,624
  • 2
  • 11
  • 27
Raya Nasiri
  • 151
  • 2
  • 14
  • `data` is a JavaScript object, not a DOM tree. See [this](https://github.com/Leonidas-from-XIV/node-xml2js#description). – robertklep Aug 30 '16 at 11:32

1 Answers1

2

To remove a property from a JavaScript object, simply set the property to undefined:

result.name = undefined;

Result from xml2js:

{
    "name": "I will get deleted",
    "items": [
        {
            "itemName": "Item 1",
            "itemLocation": "item1.htm"
        },
        {
            "itemName": "Item 2",
            "itemLocation": "item2.htm",
        }
    ]
}

After setting to undefined:

{
    "items": [
        {
            "itemName": "Item 1",
            "itemLocation": "item1.htm"
        },
        {
            "itemName": "Item 2",
            "itemLocation": "item2.htm",
        }
    ]
}

For you, this would be

result.data[3] == undefined;

Tip: you can use JSON.stringify to help you.

Smile4ever
  • 3,491
  • 2
  • 26
  • 34