1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
| <!DOCTYPE html>
<html lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Démo sauvegarde d'une table en xml</title>
<style>
table {border-collapse: collapse; }
table, td {border: 1px solid black;}
td {padding: 5px;}
#buttonToolBar {padding: 5px 0;}
</style>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<div id="buttonToolBar">
<button type="button" id="buttonSave">Sauver en XML</button>
</div>
<table id="matable">
<thead>
<td>col 1</td>
<td>col 2</td>
<td>col 3</td>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>a</td>
<td>b</td>
<td>c</td>
</tr>
<tr>
<td>truc</td>
<td>machin</td>
<td>bidule & <bidule></td>
</tr>
</tbody>
</table>
<script type="text/javascript">
function encodeAndEscapeXML(string) {
if ($.trim(string) != "") {
string = string.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
string = string.replace(/&(?!(amp;)|(lt;)|(gt;)|(quot;)|(#39;)|(apos;))/g, "&");
string = string.replace(/([^\\])((\\\\)*)\\(?![\\/{])/g, "$1\\\\$2"); //replaces odd backslash(\\) with even.
}
else {
string = "";
}
return string;
}
function tableToXML(selector) {
var xml = "<table>";
$(selector) .find("tr").each(
function() {
xml += "<row>";
$(this).find("td").each(
function() {
xml+= "<col>" + encodeAndEscapeXML($(this).html()) + "</col>";
});
xml += "</row>";
} );
xml += "</table>";
return xml;
}
function saveXMLFile (name, data) {
saveFile(name, 'text/xml, application/xml', data);
}
function saveFile (name, type, data) {
if (data != null && navigator.msSaveBlob)
return navigator.msSaveBlob(new Blob([data], { type: type }), name);
var $a = $("<a style='display: none;'/>");
var url = window.URL.createObjectURL(new Blob([data], {type: type}));
$a.attr("href", url);
$a.attr("download", name);
$("body").append($a);
$a[0].click();
window.URL.revokeObjectURL(url);
$a.remove();
}
$( document ).ready(function() {
$("#buttonSave").click(function() {
saveXMLFile("matable.xml", tableToXML("#matable"));
});
});
</script>
</body>
</html> |
Partager