Skip to content

Instantly share code, notes, and snippets.

@kmjayadeep
Created March 10, 2017 16:52
Show Gist options
  • Save kmjayadeep/a924df96d342f94147100e6a2182d157 to your computer and use it in GitHub Desktop.
Save kmjayadeep/a924df96d342f94147100e6a2182d157 to your computer and use it in GitHub Desktop.
Simple xml parser example
<html>
<head>
<title>
XML Parser
</title>
<style>
body {
font-family: monospace;
}
.head {
font-size: 3em;
text-align: center;
}
.container {
box-sizing: border-box;
}
.container:after {
content: '';
display: block;
clear: both;
}
.container .left,
.container .right {
width: calc(50% - 20px);
padding: 10px;
}
.left {
float: left;
}
.right {
float: right;
}
#xml-input {
width: 100%;
height: 400px;
resize: none;
}
table {
width: 100%;
}
</style>
</head>
<body onload="parse()">
<h1 class="head">XML Parser</h1>
<div class="container">
<div class="left">
<textarea id="xml-input" onchange="parse()"><persons>
<person>
<name>Jayadeep</name>
<college>College of engineeering trivandrum</college>
</person>
<person>
<name>Ramu</name>
<college>College of engineeering Attappadi</college>
</person>
</persons></textarea>
</div>
<div class="right">
<table>
<thead>
<tr>
<th>
Name
</th>
<th>
College
</th>
</tr>
</thead>
<tbody id="parsed-data">
</tbody>
</table>
</div>
</div>
<script>
function parse() {
var data = document.getElementById('xml-input').value
var parser = new DOMParser()
try {
var root = parser.parseFromString(data, 'text/xml')
var result = Array.from(root.firstChild.children).map(function(child) {
return '<tr><td>$name</td><td>$college</td></tr>'
.replace('$name', child.children[0].firstChild.data)
.replace('$college', child.children[1].firstChild.data)
}).join('')
} catch (err) {
result = '<tr><td style="color:red">Unable to parse xml</td></tr>'
}
document.getElementById('parsed-data').innerHTML = result
}
document.getElementById('xml-input').addEventListener('input',parse)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment