»
Tiếng AnhTiếng PhápTiếng Việt

In - Trình tạo XML đơn giản với JavaScript - JavaScriptBank.com

Phiên bản đầy đủ: jsB@nk » Ứng dụng » Công cụ xuất » Trình tạo XML đơn giản với JavaScript
URL: https://www.javascriptbank.com/xmlwriter-simple-javascript-xml-creator.html

Trình tạo XML đơn giản với JavaScript © JavaScriptBank.comXML - một kiểu định dạng dữ liệu đang ngày càng phổ biến bởi tính cơ động của nó, những mô tả trực quan của nó đối với dữ liệu làm cho các ứng dụng dễ dàng truy vấn hơn. Định dạng dữ liệu này ngày càng được sử dụng nhiều hơn bởi các ứng dụng web trên nền JavaScript, PHP, .NET, Java, Flash, ... do chúng ta chỉ cần một chuẩn dữ liệu lưu trữ sau đó truy vấn trên mọi nền tảng.Hầu hết các công cụ phát triển web cũng đều có những thư viện (hàm hoặc đối tượng) chuyên dụng để xử lí dữ liệu dạng XML này, bên cạnh đó các nền tảng khác như WordPress, Zend, Joomla, ... cũng xây dựng riêng các thư viện để xử lý XML; điều này đủ để chứng tỏ tính hiệu quả của dạng dữ liệu XML mà jsB@nk đang nói ở trên.Tuy nhiên, lĩnh vực XML rất rộng lớn, có rất nhiều quyển sách nói về XML có số trang lên đến vài nghìn; đó không phải là điều jsB@nk muốn đề cập đến trong bài viết này. jsB@nk chỉ muốn giới thiệu với bạn một ứng dụng JavaScript đơn giản để thực hiện việc xuất dữ liệu ra dạng XML. Bạn vui lòng vài trang ví dụ mẫu JavaScript để xem chi tiết hướng dẫn, giải thích ngắn: bên trái là một đoạn JavaScript mẫu, bên phải là kết quả xuất.

Phiên bản đầy đủ: jsB@nk » Ứng dụng » Công cụ xuất » Trình tạo XML đơn giản với JavaScript
URL: https://www.javascriptbank.com/xmlwriter-simple-javascript-xml-creator.html



JavaScript
<script type="text/javascript">// Created by: Ariel Flesler | http://flesler.blogspot.com/2008/03/xmlwriter-for-javascript.html// Licensed under: BSD License// This script downloaded from www.JavaScriptBank.com/** * XMLWriter - XML generator for Javascript, based on .NET's XMLTextWriter. * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com * Licensed under BSD (http://www.opensource.org/licenses/bsd-license.php) * Date: 3/12/2008 * @version 1.0.0 * @author Ariel Flesler * http://flesler.blogspot.com/2008/03/xmlwriter-for-javascript.html */ function XMLWriter( encoding, version ){if( encoding )this.encoding = encoding;if( version )this.version = version;};(function(){XMLWriter.prototype = {encoding:'ISO-8859-1',// what is the encodingversion:'1.0', //what xml version to useformatting: 'indented', //how to format the output (indented/none)  ?indentChar:'\t', //char to use for indentindentation: 1, //how many indentChar to add per levelnewLine: '\n', //character to separate nodes when formatting//start a new document, cleanup if we are reusingwriteStartDocument:function( standalone ){this.close();//cleanupthis.stack = [ ];this.standalone = standalone;},//get back to the rootwriteEndDocument:function(){this.active = this.root;this.stack = [ ];},//set the text of the doctypewriteDocType:function( dt ){this.doctype = dt;},//start a new node with this name, and an optional namespacewriteStartElement:function( name, ns ){if( ns )//namespacename = ns + ':' + name;var node = { n:name, a:{ }, c: [ ] };//(n)ame, (a)ttributes, (c)hildrenif( this.active ){this.active.c.push(node);this.stack.push(this.active);}elsethis.root = node;this.active = node;},//go up one node, if we are in the root, ignore itwriteEndElement:function(){this.active = this.stack.pop() || this.root;},//add an attribute to the active nodewriteAttributeString:function( name, value ){if( this.active )this.active.a[name] = value;},//add a text node to the active nodewriteString:function( text ){if( this.active )this.active.c.push(text);},//shortcut, open an element, write the text and closewriteElementString:function( name, text, ns ){this.writeStartElement( name, ns );this.writeString( text );this.writeEndElement();},//add a text node wrapped with CDATAwriteCDATA:function( text ){this.writeString( '<![CDATA[' + text + ']]>' );},//add a text node wrapped in a commentwriteComment:function( text ){this.writeString('<!-- ' + text + ' -->');},//generate the xml string, you can skip closing the last nodesflush:function(){if( this.stack && this.stack[0] )//ensure it's closedthis.writeEndDocument();var chr = '', indent = '', num = this.indentation,formatting = this.formatting.toLowerCase() == 'indented',buffer = '<&#63;xml version="'+this.version+'" encoding="'+this.encoding+'"';/**modded by Phong Thai @ JavaScriptBank.com*/buffer = buffer.replace( '&#63;', '?' );if( this.standalone !== undefined )buffer += ' standalone="'+!!this.standalone+'"';buffer += ' ?>';buffer = [buffer];if( this.doctype && this.root )buffer.push('<!DOCTYPE '+ this.root.n + ' ' + this.doctype+'>'); if( formatting ){while( num-- )chr += this.indentChar;}if( this.root )//skip if no element was addedformat( this.root, indent, chr, buffer );return buffer.join( formatting ? this.newLine : '' );},//cleanup, don't use again without calling startDocumentclose:function(){if( this.root )clean( this.root );this.active = this.root = this.stack = null;},getDocument: window.ActiveXObject ? function(){ //MSIEvar doc = new ActiveXObject('Microsoft.XMLDOM');doc.async = false;doc.loadXML(this.flush());return doc;}: function(){// Mozilla, Firefox, Opera, etc.return (new DOMParser()).parseFromString(this.flush(),'text/xml');}};//utility, you don't need itfunction clean( node ){var l = node.c.length;while( l-- ){if( typeof node.c[l] == 'object' )clean( node.c[l] );}node.n = node.a = node.c = null;};//utility, you don't need itfunction format( node, indent, chr, buffer ){var xml = indent + '<' + node.n,nc = node.c.length,attr, child, i = 0;for( attr in node.a )xml += ' ' + attr + '="' + node.a[attr] + '"';xml += nc ? '>' : ' />';buffer.push( xml );if( nc ){do{child = node.c[i++];if( typeof child == 'string' ){if( nc == 1 )//single text nodereturn buffer.push( buffer.pop() + child + '</'+node.n+'>' );else //regular text nodebuffer.push( indent+chr+child );}else if( typeof child == 'object' ) //element nodeformat(child, indent+chr, chr, buffer);}while( i < nc );buffer.push( indent + '</'+node.n+'>' );}};})();</script>


HTML
<script type="text/javascript">var xw = new XMLWriter('UTF-8');xw.formatting = 'indented';//add indentation and newlinesxw.indentChar = ' ';//indent with spacesxw.indentation = 2;//add 2 spaces per levelxw.writeStartDocument( );xw.writeDocType('"items.dtd"');xw.writeStartElement( 'items' );xw.writeComment('button');xw.writeStartElement('item');xw.writeAttributeString( 'id', 'item-1');xw.writeAttributeString( 'enabled', 'true' );xw.writeStartElement( 'code');xw.writeCDATA( '<button>Save</button>' );xw.writeEndElement();xw.writeElementString('description', 'a save button');xw.writeEndElement();xw.writeComment('image');xw.writeStartElement('item');xw.writeAttributeString( 'id', 'item-2');xw.writeAttributeString( 'enabled', 'false' );xw.writeStartElement( 'code');xw.writeCDATA( '<img src="photo.gif" alt="me" />' );xw.writeEndElement();xw.writeElementString('description', 'a pic of myself!');xw.writeEndElement();xw.writeComment('link');xw.writeStartElement('item');xw.writeAttributeString( 'id', 'item-3');xw.writeAttributeString( 'enabled', 'true' );xw.writeStartElement( 'code');xw.writeCDATA( '<a href="http://google.com">Google</a>' );xw.writeEndElement();xw.writeElementString('description', 'a link to Google');xw.writeEndElement();xw.writeEndElement();xw.writeEndDocument();var xml = xw.flush(); //generate the xml stringxw.close();//clean the writerxw = undefined;//don't let visitors use it, it's closed//set the xmldocument.getElementById('parsed-xml').value = xml;</script>