How to delete nodes from xml file?

2019-09-16 10:59发布

问题:

I want to manipulate a data from an XML file with Appcelerator's app.

So I'm able to read the information from this xml file with this code:

var file = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory,'/XML/file.xml'); 
var xmltext = file.read().text;
var doc = Ti.XML.parseString(xmltext); 
var nodes = doc.documentElement.getElementsByTagName("code");
for (var i=0;i<nodes.length;i++) {
    var element = nodes.item(i);
    //LA SECTION CODE DEL SOCIAL HISTORY, DEVE ESSERE
    //29762-2
    if(element.getAttribute('code') == '29762-2'){
        var section = element.parentNode;   
        if(section.nodeName =='section'){
            var entries = section.getElementsByTagName("entry");
        }
    }
}

With this code, I can read every node of my XML file. Now I want to delete some section from this XML file.

How can I do this?

EDIT

This is the code that I used to remove a child from my XML file.

var section = element.parentNode;   
var entries = section.getElementsByTagName("entry");
for(var e=0; e< entries.length; e++){
   var entry = entries.item(e);
   var nodiRimasti = section.removeChild(entry);
}

If I try to inspect on a child of section I can see that one node is removed. Now I don't know how can I confirm this modify, then saved the modify the file.

回答1:

After you've used parseString you get an XML Document which has tons of methods you can use. Look at the documentation what you can use.

For example, you can use the removeChild method to remove a child element which basically is what you're asking.

Once you've removed it, parse the XML document back to a string and update the file using the filesystem API's