Last active
April 12, 2019 04:12
-
-
Save Kshitij09/63c92e76d0e0813dc34d0f48d3500eb5 to your computer and use it in GitHub Desktop.
Javascript code to open an xml file from client machine and parse its contents
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* <input type="file" id="xmlFile" /> | |
* include this tag in your html file | |
* you can use the following xml file for testing | |
* file URL: https://drive.google.com/file/d/1Ifef0RCqCq5apRT2LQbB6HguD43VpTXF/view?usp=sharing | |
*/ | |
document.querySelector('#xmlFile').addEventListener('change', readFile, false); | |
function readFile(e) { | |
const file = e.target.files[0]; | |
const reader = new FileReader(); | |
reader.onload = parseXml; | |
reader.readAsText(file); | |
} | |
const parseXml = (e) => { | |
const xml = e.target.result; | |
console.log(xml); | |
let xmlDoc; | |
if (window.DOMParser) | |
{ | |
const parser = new DOMParser(); | |
xmlDoc = parser.parseFromString(xml, "text/xml"); | |
} else { | |
xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); | |
xmlDoc.async = false; | |
xmlDoc.loadXML(xml); | |
} | |
const records = xmlDoc.getElementsByTagName('employee'); | |
for (let i = 0; i < records.length; i++) { | |
records[i].childNodes.forEach((node) => { | |
if (node.nodeType == 1) { | |
console.log(node.childNodes[0].nodeValue); | |
} | |
}); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment