xml read

aa.html

<html>
<head>

</head>
<body>
<input type=”file” onchange=”readfile(this)” >

<script>
function xml2json(xml) {
try {
var obj = {};
if (xml.children.length > 0) {
for (var i = 0; i < xml.children.length; i++) {
var item = xml.children.item(i);
var nodeName = item.nodeName;

if (typeof (obj[nodeName]) == “undefined”) {
obj[nodeName] = xml2json(item);
} else {
if (typeof (obj[nodeName].push) == “undefined”) {
var old = obj[nodeName];

obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xml2json(item));
}
}
} else {
obj = xml.textContent;
}
return obj;
} catch (e) {
console.log(e.message);
}
};

function readfile(fileinputobj){
var reader = new FileReader();

reader.onload = function(e) {
//alert(reader.result);
//Using DOMParser to get XMLDocument
var parser = new DOMParser(),
xmlDoc = parser.parseFromString(reader.result, “text/xml”);

if (xmlDoc.documentElement){
console.log(xmlDoc.documentElement);
var oJson = xml2json(xmlDoc.documentElement);
console.log(“json(to) : ” + oJson.to);
console.log(“json(from) : ” + oJson.from);
//xmlDoc.documentElement.nodeName == ‘urlset’
}

//Using DOM interpreter to get HtmlDocument
var doc=document.createElement(“div”);
doc.innerHTML=reader.result;
if (doc.querySelector(‘urlset’)){
console.log(doc.querySelector(‘urlset’));
//doc.querySelector(‘urlset’).tagName == ‘urlset’
}
}

reader.readAsText(fileinputobj.files[0]);
}
</script>
</body>
</html>

 

aa.xml

<?xml version=”1.0″ encoding=”UTF-8″?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don’t forget me this weekend!</body>
</note>