Stuk / jszip

Create, read and edit .zip files with Javascript
https://stuk.github.io/jszip/
Other
9.82k stars 1.3k forks source link

Extracting xml file #497

Open africantearoa opened 6 years ago

africantearoa commented 6 years ago

Hi,

I'm struggling to extract the xml content from a zip file. Wondered if anyone knew the best way to do so.

var new_zip = new JSZip();
// loading a zip file
JSZipUtils.getBinaryContent("testfile.zip", function (err, data) {
    if(err) {
        throw err; // or handle the error
    }
    new_zip.loadAsync(data)
        .then(function(zip) {
            // you now have every files contained in the loaded zip
            zip.forEach(function (relativePath, file) {
                if(relativePath.split(".")[1]==="xml"){

                    //???

                }
            })
        });
});
africantearoa commented 6 years ago

Think I've found it - was in the ZipEntry documentation but I couldn't understand what was going on with that and had to look elsewhere for an example that used it. FYI this is the current code. Needed to add a separate function to put the string data into an ActiveXObject to be able to parse it like an XML file.

var new_zip = new JSZip();
// loading a zip file
JSZipUtils.getBinaryContent("test.zip", function (err, data) {
    if(err) {
        throw err; // or handle the error
    }
    new_zip.loadAsync(data)
        .then(function(zip) {
            // you now have every files contained in the loaded zip
            zip.forEach(function (relativePath, file) {

                if(relativePath.split(".")[1]==="xml"){

                    file.async("string").then(function (data) {
                        //ParseXML is my function that parses the ActiveXObject
                        //stringToXML converts the string to an ActiveXObject
                        parseXML(stringToXML(data));

                    });

                }

            })
        });
});

function stringToXML(oString) {
    //code for IE
    if (window.ActiveXObject) {
        var oXML = new ActiveXObject("Microsoft.XMLDOM"); oXML.loadXML(oString);
        return oXML;
    }
    // code for Chrome, Safari, Firefox, Opera, etc.
    else {
        return (new DOMParser()).parseFromString(oString, "text/xml");
    }
}

Now to figure out how to extract images...

Tinysusie commented 5 years ago

hi~ I want to ask, is this function ( file.async("string").then... ) works on IE(11)? my code like yours just ran error [TypeError] on IE11.

africantearoa commented 5 years ago

I think it should work on IE11

Tinysusie commented 5 years ago

I think it should work on IE11

ok,thankU