Permalink
Browse files

meet nodejs and support doctype parsing

  • Loading branch information...
1 parent 4da7ce0 commit 79055697a69345f8e9b66b78f21fe50f561117de @colorhook committed Mar 29, 2012
Showing with 461 additions and 2,033 deletions.
  1. +61 −56 README.md
  2. +0 −6 build/jsxml-0.1.0-yui.js
  3. +0 −1,647 build/jsxml-0.1.0.js
  4. +165 −165 examples/d2forum.html
  5. +74 −74 examples/weather.html
  6. +127 −83 src/jsxml.js
  7. +34 −2 tests/jsxml-test.js
View
117 README.md
@@ -1,92 +1,97 @@
jsxml
==============
-jsxml is an XML library for javascript
+jsxml is an XML library for javascript (and node)
How to use?
------------
After add this library to your project, there will be a global object named jsxml.
-
- var Namespace = jsxml.Namespace,
- QName = jsxml.QName,
- XML = jsxml.XML,
- XMLList = jsxml.XMLList;
-
+```javascript
+var Namespace = jsxml.Namespace,
+ QName = jsxml.QName,
+ XML = jsxml.XML,
+ XMLList = jsxml.XMLList;
+```
Here you go:
+```javascript
+var xml = new XML("your xml string");
- var xml = new XML("your xml string");
-
- //find child nodes
- var child = xml.child('childTag');
+//find child nodes
+var child = xml.child('childTag');
- //find descendants nodes
- var descendants = xml.descendants('descendantTag');
+//find descendants nodes
+var descendants = xml.descendants('descendantTag');
- //get all children
- var children = xml.children();
- //or
- var children = xml.child('*');
+//get all children
+var children = xml.children();
+//or
+var children = xml.child('*');
- //get text node
- var text = xml.text();
+//get text node
+var text = xml.text();
- //get element node
- var elements = xml.elements();
+//get element node
+var elements = xml.elements();
- //get comment node
- var comments = xml.comments();
+//get comment node
+var comments = xml.comments();
- //get attribute
- var attribute = xml.attribute("attributeName");
+//get attribute
+var attribute = xml.attribute("attributeName");
- //get all attributes
- var attributes = xml.attributes();
+//get all attributes
+var attributes = xml.attributes();
+```
All methods above return an XML object or XMLList object, if you want to get the String type content, you should:
+```javascript
+var xml = new XML("your xml string");
- var xml = new XML("your xml string");
-
- var attrValue = xml.attribute('attrName').toString();
- //or
- var attrValue = xml.attribute('attrName').getValue();
-
- var childA = xml.child('a').getValue();
- //or
- var childA = xml.child('a').getValue();
+var attrValue = xml.attribute('attrName').toString();
+//or
+var attrValue = xml.attribute('attrName').getValue();
+var childA = xml.child('a').toString();
+//or
+var childA = xml.child('a').getValue();
+```
If you want to modify the value, you should call method setValue:
+```javascript
+var xml = new XML("your xml string");
- var xml = new XML("your xml string");
+var attr= xml.attribute('attrName');
+attr.setValue("newValue");
- var attr= xml.attribute('attrName');
- attr.setValue("newValue");
-
- var childA = xml.child('a');
- childA.setValue("newValue");
+var childA = xml.child('a');
+childA.setValue("newValue");
+```
You can regenerate the XML
-
- var str = xml.toXMLString();
+```javascript
+var str = xml.toXMLString();
+```
While dealing with a list of childs in XML tree, you should use XMLList API:
-
- var list = xml.child("item");
- list.each(function(item, index){
- //item is an XML
- });
+```javascript
+var list = xml.child("item");
+list.each(function(item, index){
+//item is an XML
+});
+```
Advanced topics
----------------
You can also add, retrieve or remove namespaces:
-
- var xml = new XML("your xml string");
- var ns = xml.namespace("prefix");
-
- var nsNew = new Namespace("prefix", 'uri');
- xml.addNamespace(nsNew);
- xml.removeNamespace(nsNew);
+```javascript
+var xml = new XML("your xml string");
+var ns = xml.namespace("prefix");
+
+var nsNew = new Namespace("prefix", 'uri');
+xml.addNamespace(nsNew);
+xml.removeNamespace(nsNew);
+```
Bugs & Feedback
----------------
View
6 build/jsxml-0.1.0-yui.js
@@ -1,6 +0,0 @@
-/*
- * Copyright 2011 http://colorhook.com.
- * @author: <a href="colorhook@gmail.com">colorhook</a>
- * @version:0.1.0
- */
-var jsxml=(function(){var n=/^<([a-zA-Z\$_]+:{0,1}[a-zA-Z0-9\$\-_]*)((?:\s+[a-zA-Z\$_]+:{0,1}[a-zA-Z0-9\$\-_]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/,f=/^<\/([a-zA-Z0-9\$\-_:]+)[^>]*>/,j=/([a-zA-Z\$_]+:{0,1}[a-zA-Z0-9\$\-_]*)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g,b,c,m,o,g,e,h,d,l,i,k,a;c=String.prototype.trim?function(p){return p&&p.trim?p.trim():p}:function(p){try{return p.replace(/^\s+|\s+$/,"")}catch(q){return p}};m=function(r,p){for(var q in p){if(p.hasOwnProperty(q)){r[q]=p[q]}}if(!-[1,]){if(p.toString!==Object.prototype){r.toString=p.toString}}};arrayIndexOf=function(s,r){if(s.indexOf){return s.indexOf(r)}for(var q=0,p=s.length;q<p;q++){if(r===s[q]){return q}}return -1};o=function(p){return p.match(/&(amp|lt|gt);/)};g=function(p){p=p.replace(/&[^(amp;|lt;|gt;)]/g,"&amp;");p=p.replace(/</g,"&lt;");p=p.replace(/>/g,"&gt;");return p};e=function(p){p=p.replace(/&lt;/g,"<");p=p.replace(/&gt;/g,">");p=p.replace(/&amp;/g,"&");return p};b=function(q,y){var t,u,r,v=[],w=q;v.last=function(){return this[this.length-1]};while(q){u=true;if(q.indexOf("<![CDATA[")==0){t=q.indexOf("]]>");if(t>0){x=q.substring(9,t);if(y.chars){y.chars(x,true)}q=q.substring(t+3)}u=false}else{if(q.indexOf("<?")==0){t=q.indexOf("?>");if(t>0){x=q.substr(2,t-2);if(y.instruction){y.instruction(x)}q=q.substring(t+2)}u=false}else{if(q.indexOf("<!--")==0){t=q.indexOf("-->");if(t>=0){if(y.comment){y.comment(q.substring(4,t))}q=q.substring(t+3);u=false}}else{if(q.indexOf("</")==0){r=q.match(f);if(r){q=q.substring(r[0].length);r[0].replace(f,s);u=false}}else{if(q.indexOf("<")==0){r=q.match(n);if(r){q=q.substring(r[0].length);r[0].replace(n,p);u=false}}}}}}if(u){t=q.indexOf("<");var x=t<0?q:q.substring(0,t);q=t<0?"":q.substring(t);if(y.chars){y.chars(x)}}if(q==w){throw"Parse Error: "+q}w=q}s();function p(z,C,D,A){A=!!A;if(!A){v.push(C)}if(y.start){var B=[];D.replace(j,function(F,E){var G=arguments[2]?arguments[2]:arguments[3]?arguments[3]:arguments[4]?arguments[4]:E?E:"";B.push({name:E,value:G,escaped:G.replace(/(^|[^\\])"/g,'$1\\"')})});if(y.start){y.start(C,B,A)}}}function s(z,B){if(!B){var C=0}else{for(var C=v.length-1;C>=0;C--){if(v[C]==B){break}}}if(C>=0){for(var A=v.length-1;A>=C;A--){if(y.end){y.end(v[A])}}v.length=C}}};h=function(r,q){var p=arguments.length;if(p>=2){this.prefix=String(r);this.uri=String(q)}else{if(p==1){this.prefix="";this.uri=String(r)}else{this.prefix="";this.uri=""}}};h.prototype={constructor:h,toString:function(){return this.uri},copy:function(){var p=new h();p.prefix=this.prefix;p.uri=this.uri;return p},equals:function(p){return this.prefix===p.prefix&&this.uri===p.uri}};d=function(r,q){var p=arguments.length;if(p>=2){this.uri=String(r);this._ns=(r&&r.constructor==h)?r:new h(r);this.localName=String(q)}else{if(p==1){this.uri="";this._ns=new h();this.localName=String(r)}else{this.uri="";this._ns=new h();this.localName=""}}};d.prototype={constructor:d,toString:function(){var p=this.uri?this.uri+"::":"";return p+this.localName},copy:function(){var p=new d();p.uri=this.uri;p.localName=this.localName;p._ns=this._ns.copy();return p},equals:function(p){return this.localName==p.localName&&this._ns.equals(p._ns)}};d._format=function(r,t){var q=r.split(":"),s,p;if(q.length==2){s=q[0];p=q[1]}else{s="";p=r}return new d(new h(s,t),p)};l={ELEMENT:"element",COMMENT:"comment",PROCESSING_INSTRUCTIONS:"processing-instructions",TEXT:"text",ATTRIBUTE:"attribute"};i=function(p){if(p._list&&p.length()==1){return i(p._list[0])}return p};k=function(){this._list=[]};m(k.prototype,{constructor:k,_addXML:function(p){if(p.constructor==a){this._list.push(p)}else{if(p.constructor==k){this._list=this._list.concat(p._list)}}return this},length:function(){return this._list.length},childIndex:function(){throw new Error("this method only availabe in single list XML")},child:function(r){var q=new k();this.each(function(p){var s=p.child(r);if(s.length()){q._addXML(s)}});return i(q)},children:function(){return this.child("*")},attribute:function(r){var q=new k();this.each(function(p){q._addXML(p.attribute(r))});return i(q)},attributes:function(q){return this.attribute("*")},elements:function(r){var q=new k();this.each(function(p){q._addXML(p.elements(r))});return i(q)},descendants:function(r){var q=new k();this.each(function(p){q._addXML(p.descendants(r))});return i(q)},normalize:function(){this.each(function(p){p.normalize()})},hasSimpleContent:function(){for(var q=0,p=this._list.length;q<p;q++){var r=this._list[q];if(r.constructor==k||r.hasComplexContent()){return false}}return true},hasComplexContent:function(){return !this.hasSimpleContent()},text:function(){var p=new k();this.each(function(r){if(r.constructor==a){var q=r.text();if(q._text!=""){p._addXML(q)}}});return i(p)},comments:function(){var p=new k();this.each(function(q){if(q.constructor==a){p._addXML(q.comments())}});return i(p)},processingInstructions:function(){var p=new k();this.each(function(q){if(q.constructor==a){p._addXML(q.processingInstructions())}});return i(p)},copy:function(){var p=new k();this.each(function(r,q){p._list[q]=r.copy()});return p},toXMLString:function(){var p=[];this.each(function(q){p.push(q.toXMLString())});return p.join("\n")},toString:function(){var p="";this.each(function(q){p+=q.toString()});return p},item:function(p){return this._list[p]},each:function(r){for(var q=0,p=this._list.length;q<p;q++){r(this._list[q],q,this)}}});a=function(r){this._children=[];this._attributes=[];this._namespaces=[];this._nodeKind=l.ELEMENT;this._qname=null;this._parent=null;this._text=null;this._useCDATA=false;var q,p=this;if(r){b(r,{start:function(A,z,s){var v;if(!q){v=p}else{v=new a();v._parent=q}v._qname=d._format(A);for(var u in z){var x=new a();x._nodeKind=l.ATTRIBUTE;var t;if(z[u].name==="xmlns"){t=new d(new h("xmlns",z[u].value),"")}else{t=d._format(z[u].name,z[u].value)}var w=t._ns.prefix||"";if(w==="xmlns"){var y=new h(t.localName,t.uri);v.addNamespace(y);if(t.localName==v._qname._ns.prefix){v.setNamespace(y)}}else{x._qname=t;x._text=z[u].value;v._attributes.push(x)}}q=v;if(s){this.end(A)}},chars:function(u,s){u=c(u);if(u==""&&a.ignoreWhitespace){return}var t=new a();t._nodeKind=l.TEXT;t._text=u;t._useCDATA=s;q._children.push(t)},end:function(s){if(q&&q._parent){q._parent._children.push(q);q=q._parent}else{if(q==p){q=null}}},comment:function(t){var s=new a();s._nodeKind=l.COMMENT;s._text=t;q&&q._children.push(s)},instruction:function(t){var s=new a();s._nodeKind=l.PROCESSING_INSTRUCTIONS;s._text=t;q&&q._children.push(s)}})}};m(a.prototype,{addNamespace:function(p){if(p.prefix!=undefined){this.removeNamespace(p);this._namespaces.push(p)}},removeNamespace:function(r){for(var q=0,p=this._namespaces.length;q<p;q++){if(r.prefix==this._namespaces[q].prefix){this._namespaces.splice(q,1);break}}},namespace:function(r){if(!r){return new h()}for(var q=0,p=this._namespaces.length;q<p;q++){if(r==this._namespaces[q].prefix){return this._namespaces[q]}}return undefined},setNamespace:function(p){if(p&&p.constructor==h){this.addNamespace(p);if(this._qname){this._qname.uri=p.uri;this._qname._ns=p}}},namespaceDeclarations:function(){return this._namespaces},inScopeNamespaces:function(){var q=this._namespaces;var p=this._parent;while(p){q=p.inScopeNamespaces().concat(q);p=p._parent}return q},nodeKind:function(){return this._nodeKind},name:function(){if(!this._qname){return null}if(this._qname.uri){return this._qname.uri+":"+this._qname.localName}return this._qname.localName},localName:function(){if(!this._qname){return null}return this._qname.localName},setName:function(p){if(this._qname==null){return}if(/^[a-zA-Z]+[a-zA-Z0-9]*$/.test(p)){this._qname.uri="";this._qname.localName=p}else{throw new Error("invalid value for XML name")}},setLocalName:function(p){if(this._qname==null){return}if(/^[a-zA-Z\$_]+[a-zA-Z0-9\$\-_]*$/.test(p)){this._qname.localName=p}else{throw new Error("invalid value for XML localName")}},length:function(){return 1},attribute:function(v){var r=this._attributes,s,q,t,u=new k();for(s=0,q=r.length;s<q;s++){t=r[s];if(t._qname.localName==v||v=="*"){u._addXML(t)}}return i(u)},attributes:function(){return this.attribute("*")},_createTextNode:function(q){var p=new a();p._nodeKind=l.TEXT;p._text=q;p._useCDATA=/['"<>&]/.test(q);return p},appendChild:function(r){var q=r.constructor;if(q==a){r._parent=this;this._children.push(r)}else{if(q==k){r.each(function(s){s._parent=this});this._children=this._children.concat(r._list)}else{if(q==String){var p=this._createTextNode(r);p._parent=this;this._children.push(p)}}}return this},prependChild:function(r){var q=r.constructor;if(q==a){r._parent=this;this._children.unshift(r)}else{if(q==k){r.each(function(s){s._parent=this});this._children=this._list.concat(this._children)}else{if(q===String){var p=this._createTextNode(r);p._parent=this;this._children.unshift(p)}}}return this},normalize:function(){var s,p,t,r=this._children,v=[];for(s=0,p=r.length;s<p;s++){var u=r[s],q=u.nodeKind();if(q==l.TEXT){if(t){u._text=t._text+u._text;r[s-1]=null}t=u}else{if(q==l.ELEMENT){u.normalize();t=null}}}for(s=0,p=r.length;s<p;s++){r[s]&&v.push(r[s])}this._children=v},_getFilterChildren:function(){var s,p,u=[],r=this._children;for(s=0,p=r.length;s<p;s++){var t=r[s],q=t.nodeKind();if(q==l.ELEMENT||q==l.TEXT||(q==l.COMMENT&&!a.ignoreComments)||(q==l.PROCESSING_INSTRUCTIONS&&!a.ignoreProcessingInstructions)){u.push(t)}}return u},child:function(u){var t=new k(),s,q,v=this._getFilterChildren();if(typeof u=="number"){if(v.length!=0&&v[u]){t._addXML(v[u])}}else{for(s=0,q=v.length;s<q;s++){var r=v[s];if(r.localName()==u||u=="*"){t._addXML(r)}}}return i(t)},childIndex:function(q){if(this._parent){return arrayIndexOf(this._parent._getFilterChildren(),this)}return -1},children:function(){return this.child("*")},setChildren:function(p){this._children=[];return this.appendChild(p)},replace:function(y,x){var z=-1,u,s,w=this._children,q=[];for(u=0,s=w.length;u<s;u++){var v=w[u],p=v.nodeKind();if((v.localName()==y||y=="*")&&p==l.ELEMENT){if(z==-1){z=u;var r=x.constructor;if(r==a){x._parent=this;q.push(x)}else{if(r==k){x.each(function(t){t._parent=this});q=q.concat(x._list)}else{if(r===String){var A=this._createTextNode(x);A._parent=this;q.push(A)}}}}}else{q.push(v)}}if(z!=-1){this._children=q;this.normalize()}return this},elements:function(u){if(arguments.length==0){u="*"}var t=new k(),s,q,v=this._children;for(s=0,q=v.length;s<q;s++){var r=v[s];if((r.localName()==u||u=="*")&&r.nodeKind()==l.ELEMENT){t._addXML(r)}}return i(t)},descendants:function(v){if(arguments.length==0){v="*"}var u=new k(),t,q,w=this._children;for(t=0,q=w.length;t<q;t++){var s=w[t],r=s.nodeKind();if((s.localName()==v||v=="*")&&(r==l.ELEMENT||r==l.TEXT)){u._addXML(s)}if(s._nodeKind==l.ELEMENT){u._addXML(s.descendants(v))}}return i(u)},insertChildBefore:function(s,r){if(s==null){return this.appendChild(r)}if(s.constructor!=a){return undefined}var t=s.childIndex();if(s._parent==this&&t!=-1){if(r.constructor==a){r._parent=this;this._children.splice(t,0,r)}else{if(r.constructor==k){for(var q=0,p=r._list.length;q<p;q++){r._list[q]._parent=this;this._children.splice(t+q,0,r._list[q])}}else{return undefined}}return this}else{return undefined}},insertChildAfter:function(s,r){if(s==null){return this.prependChild(r)}if(s.constructor!=a){return undefined}var t=s.childIndex();if(s._parent==this&&t!=-1){if(r.constructor==a){r._parent=this;this._children.splice(t+1,0,r)}else{if(r.constructor==k){for(var q=0,p=r._list.length;q<p;q++){r._list[q]._parent=this;this._children.splice(t+1+q,0,r._list[q])}}else{return undefined}}return this}else{return undefined}},parent:function(){return this._parent},hasSimpleContent:function(){var s=this._children;for(var r=0,p=s.length;r<p;r++){var q=s[r].nodeKind();if(q===l.ELEMENT){return false}}return true},hasComplexContent:function(){return !this.hasSimpleContent()},comments:function(){var s=new k(),r,p,t=this._getFilterChildren();for(r=0,p=t.length;r<p;r++){var q=t[r];if(q.nodeKind()==l.COMMENT){s._addXML(q)}}return i(s)},text:function(){var u=this._children,t="";for(var s=0,p=u.length;s<p;s++){var q=u[s].nodeKind();if(q===l.TEXT){if(u[s]._useCDATA){t+=u[s]._text}else{t+=e(u[s]._text)}}}return this._createTextNode(t)},comments:function(){var s=new k(),r,p,t=this._getFilterChildren();for(r=0,p=t.length;r<p;r++){var q=t[r];if(q.nodeKind&&q.nodeKind()==l.COMMENT){s._addXML(q)}}return i(s)},processingInstructions:function(){var s=new k(),r,p,t=this._getFilterChildren();for(r=0,p=t.length;r<p;r++){var q=t[r];if(q.nodeKind&&q.nodeKind()==l.PROCESSING_INSTRUCTIONS){s._addXML(q)}}return i(s)},copy:function(){var q=new a(),r,p;q._nodeKind=this._nodeKind;q._text=this._text;q._useCDATA=this._useCDATA;if(this._qname){q._qname=this._qname.copy()}for(r=0,p=this._namespaces.length;r<p;r++){q._namespaces[r]=this._namespaces[r].copy()}for(r=0,p=this._attributes.length;r<p;r++){q._attributes[r]=this._attributes[r].copy()}for(r=0,p=this._children.length;r<p;r++){q._children[r]=this._children[r].copy()}return q},_toXMLString:function(x,C){var G="",H,A,y,t=this._nodeKind,D=C?this.inScopeNamespaces():this._namespaces,F=this._attributes,w=this._children,z=a.prettyPrinting,u=[];x=x||0;if(z){for(A=0;A<x;A++){G+=" "}}if(t==l.ATTRIBUTE){return G+this._text}else{if(t==l.TEXT){if(this._useCDATA){return G+"<![CDATA["+this._text+"]]>"}else{return G+g(this._text)}}else{if(t==l.COMMENT){return G+"<!--"+this._text+"-->"}else{if(t==l.PROCESSING_INSTRUCTIONS){return G+"<?"+this._text+"?>"}}}}if(this._qname._ns.prefix){H=this._qname._ns.prefix+":"+this.localName()}else{H=this.localName()}G+="<"+H;for(A=0,y=D.length;A<y;A++){var B=D[A].prefix?"xmlns:"+D[A].prefix:"xmlns";u.push({label:B,value:D[A].uri})}for(A=0,y=F.length;A<y;A++){var r=F[A]._qname,B=r._ns.prefix,E;if(B){E=B+":"+r.localName}else{E=r.localName}u.push({label:E,value:F[A]._text})}if(u.length>0){for(A=0,y=u.length;A<y;A++){G+=" "+u[A].label+'="'+u[A].value+'"'}}u=[];for(A=0,y=w.length;A<y;A++){var v=w[A];if(v.nodeKind()==l.ELEMENT){u.push(v)}else{if(v.nodeKind()==l.COMMENT&&!a.ignoreComments){u.push(v)}else{if(v.nodeKind()==l.PROCESSING_INSTRUCTIONS&&!a.ignoreProcessingInstructions){u.push(v)}else{if(v.nodeKind()==l.TEXT){u.push(v)}}}}}if(u.length==0){G+="/>"}else{if(u.length==1&&u[0].nodeKind()==l.TEXT){G+=">";G+=u[0]._toXMLString(0);G+="</"+H+">"}else{G+=">";for(A=0,y=u.length;A<y;A++){if(z){G+="\n"}G+=u[A]._toXMLString(x+a.prettyIndent)}if(z){G+="\n";for(A=0;A<x;A++){G+=" "}}G+="</"+H+">"}}return G},toXMLString:function(){return this._toXMLString(0,true)},toString:function(){if(this.hasComplexContent()){return this.toXMLString()}if(this.nodeKind()==l.TEXT||this.nodeKind()==l.ATTRIBUTE){return this._text}var t="";for(var q=0,p=this._children.length;q<p;q++){var r=this._children[q];if(r._nodeKind==l.TEXT){if(r._useCDATA){t+=r._text}else{t+=e(r._text)}}}return t},getValue:function(){var p=this._nodeKind;if(p==l.TEXT){if(!this._useCDATA&&o(this._text)){return e(this._text)}return this._text}else{if(p==l.ATTRIBUTE){return this._text}else{if(p==l.ELEMENT&&this.hasSimpleContent()){var q=this.text();if(q.getValue){return q.getValue()}}}}return undefined},setValue:function(u){var q=this._nodeKind;if(q==l.TEXT||q==l.ATTRIBUTE||q==l.COMMENT||q==l.PROCESSING_INSTRUCTIONS){this._text=u}else{if(q==l.ELEMENT&&this.hasSimpleContent()){var v=[],t=this._createTextNode(u);t._parent=this;v.push(t);for(var r=0,p=this._children.length;r<p;r++){var s=this._children[r];if(s._nodeKind!=l.TEXT){v.push(s)}}this._children=v}}return this}});m(a,{ignoreComments:true,ignoreProcessingInstructions:true,ignoreWhitespace:true,prettyIndent:2,prettyPrinting:true,settings:function(){return{ignoreComments:this.ignoreComments,ignoreProcessingInstructions:this.ignoreProcessingInstructions,ignoreWhitespace:this.ignoreWhitespace,prettyIndent:this.prettyIndent,prettyPrinting:this.prettyPrinting}},setSettings:function(q){if(!q){return}var p=function(r){if(q.hasOwnProperty(r)){a[r]=q[r]}};p("ignoreComments");p("ignoreProcessingInstructions");p("ignoreWhitespace");p("prettyIndent");p("prettyPrinting")}});return{containsEntity:o,replaceToEntity:g,replaceFromEntity:e,parseXML:b,Namespace:h,QName:d,NodeKind:l,XMLList:k,XML:a}})();
View
1,647 build/jsxml-0.1.0.js
@@ -1,1647 +0,0 @@
-/*!
- * Copyright 2011 http://colorhook.com.
- * @author: <a href="colorhook@gmail.com">colorhook</a>
- * @version:0.1.0
- */
-/**
- * @preserve Copyright 2011 http://colorhook.com.
- * @author: <a href="colorhook@gmail.com">colorhook</a>
- * @version:0.1.0
- */
-var jsxml = (function(){
-
- /**
- * XML parser comes from HTML Parser by John Resig (ejohn.org)
- * http://ejohn.org/files/htmlparser.js
- * Original code by Erik Arvidsson, Mozilla Public License
- * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
- */
- // Regular Expressions for parsing tags and attributes
- var startTag = /^<([a-zA-Z\$_]+:{0,1}[a-zA-Z0-9\$\-_]*)((?:\s+[a-zA-Z\$_]+:{0,1}[a-zA-Z0-9\$\-_]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/,
- endTag = /^<\/([a-zA-Z0-9\$\-_:]+)[^>]*>/,
- attr = /([a-zA-Z\$_]+:{0,1}[a-zA-Z0-9\$\-_]*)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g,
- _parseXML,
- trim,
- merge,
- containsEntity,
- replaceToEntity,
- replaceFromEntity,
- Namespace,
- QName,
- NodeKind,
- _getXMLIfLengthEqualOne,
- XMLList,
- XML;
-
- /**
- * @description trim whitespace before or after the String
- * @param s{String}
- * @return String
- */
- trim = String.prototype.trim ? function(s){
- return s && s.trim ? s.trim() : s;
- }: function(s){
- try{
- return s.replace(/^\s+|\s+$/, '');
- }catch(err){
- return s;
- }
- };
- /**
- * @description merge one object to another, used to extend object.
- * because of the toString property is not enumerable in IE browser,
- * so we must assign it explicity.
- * @param s1{Object} object need to be extended.
- * @param s2{Object} extension object
- * @return Object
- */
- merge = function(s1, s2){
- for(var i in s2){
- if(s2.hasOwnProperty(i)){
- s1[i] = s2[i];
- }
- }
- //fix IE toString() not Enumerable bug
- if(!-[1,]){
- if(s2.toString !== Object.prototype){
- s1.toString = s2.toString;
- }
- }
- };
- /**
- * @description find element's index from an array.
- * @param array{Array} the array hosting the element
- * @param ele{Object} the element in the array
- * @return Number
- */
- arrayIndexOf = function(array, ele){
- if(array.indexOf){
- return array.indexOf(ele);
- }
- for(var i = 0, l = array.length; i < l; i++){
- if(ele === array[i]){
- return i;
- }
- }
- return -1;
- };
- /**
- * @description check if the string contains XML entity format(&amp; &lt; &gt;) or not.
- * @param str{String}
- * @return Boolean
- */
- containsEntity = function(str){
- return str.match(/&(amp|lt|gt);/);
- };
- /**
- * @description convert special characters (& < >) to XML entity format.
- * @param str{String}
- * @return String
- */
- replaceToEntity = function(str){
- str = str.replace(/&[^(amp;|lt;|gt;)]/g, '&amp;');
- str = str.replace(/</g, '&lt;');
- str = str.replace(/>/g, '&gt;');
- return str;
- }
- /**
- * @description convert from XML entity format to readable characters.
- * @param str{String}
- * @return String
- */
- replaceFromEntity = function(str){
- str = str.replace(/&lt;/g, '<');
- str = str.replace(/&gt;/g, '>');
- str = str.replace(/&amp;/g, '&');
- return str;
- }
- /**
- * @description parse XML string
- * @param xml{String} XML string
- * @param handler{Object} callback handler
- * @return void
- */
- _parseXML = function(xml, handler ) {
- var index, chars, match, stack = [], last = xml;
- stack.last = function(){
- return this[ this.length - 1 ];
- };
-
- while (xml) {
- chars = true;
-
- //CDATA
- if(xml.indexOf("<![CDATA[") == 0){
-
- index = xml.indexOf("]]>");
- if(index > 0){
- text = xml.substring(9, index);
-
- if ( handler.chars )
- handler.chars( text, true );
-
- xml = xml.substring( index + 3 );
- }
- chars = false;
- }
- //instruction
- else if(xml.indexOf("<?") == 0){
- index = xml.indexOf("?>");
- if(index > 0){
- text = xml.substr(2, index-2);
- if(handler.instruction){
- handler.instruction(text);
- }
- xml = xml.substring( index + 2 );
- }
- chars = false;
- }
- // Comment
- else if ( xml.indexOf("<!--") == 0 ) {
- index = xml.indexOf("-->");
-
- if ( index >= 0 ) {
- if ( handler.comment )
- handler.comment( xml.substring( 4, index ) );
- xml = xml.substring( index + 3 );
- chars = false;
- }
-
- // end tag
- } else if ( xml.indexOf("</") == 0 ) {
- match = xml.match( endTag );
-
- if ( match ) {
- xml = xml.substring( match[0].length );
- match[0].replace( endTag, parseEndTag );
- chars = false;
- }
-
- // start tag
- } else if ( xml.indexOf("<") == 0 ) {
- match = xml.match( startTag );
- if ( match ) {
- xml = xml.substring( match[0].length );
- match[0].replace( startTag, parseStartTag );
- chars = false;
- }
- }
-
- if ( chars ) {
- index = xml.indexOf("<");
-
- var text = index < 0 ? xml : xml.substring( 0, index );
- xml = index < 0 ? "" : xml.substring( index );
-
- if ( handler.chars )
- handler.chars( text );
- }
-
-
- if ( xml == last )
- throw "Parse Error: " + xml;
- last = xml;
- }
-
- // Clean up any remaining tags
- parseEndTag();
-
- function parseStartTag(tag, tagName, rest, unary ) {
-
- unary = !!unary;
-
- if ( !unary )
- stack.push( tagName );
-
- if ( handler.start ) {
- var attrs = [];
-
- rest.replace(attr, function(match, name) {
- var value = arguments[2] ? arguments[2] :
- arguments[3] ? arguments[3] :
- arguments[4] ? arguments[4] :
- name ? name : "";
-
- attrs.push({
- name: name,
- value: value,
- escaped: value.replace(/(^|[^\\])"/g, '$1\\\"') //"
- });
- });
-
- if ( handler.start )
- handler.start( tagName, attrs, unary );
- }
- }
-
- function parseEndTag( tag, tagName ) {
- // If no tag name is provided, clean shop
- if ( !tagName )
- var pos = 0;
-
- // Find the closest opened tag of the same type
- else
- for ( var pos = stack.length - 1; pos >= 0; pos-- )
- if ( stack[ pos ] == tagName )
- break;
-
- if ( pos >= 0 ) {
- // Close all the open elements, up the stack
- for ( var i = stack.length - 1; i >= pos; i-- )
- if ( handler.end )
- handler.end( stack[ i ] );
-
- // Remove the open elements from the stack
- stack.length = pos;
- }
- }
- };
-
- /**
- * @description Namespace class
- * @access public
- * @param prefix{String} the namespace prefix
- * @param uri{String} the namespace uri.
- */
- Namespace = function(prefix, uri){
- var len = arguments.length;
- if(len >= 2){
- this.prefix = String(prefix);
- this.uri = String(uri);
- }else if(len == 1){
- this.prefix = "";
- this.uri = String(prefix);
- }else{
- this.prefix = "";
- this.uri = "";
- }
- }
-
- Namespace.prototype = {
- constructor: Namespace,
-
- /**
- * @description to string
- * @access public
- * @return String
- */
- toString: function(){
- return this.uri;
- },
- /**
- * @description return a Namespace copy object
- * @access public
- * @return Namespace
- */
- copy: function(){
- var ns = new Namespace();
- ns.prefix = this.prefix;
- ns.uri = this.uri;
- return ns;
- },
- /**
- * @description check if the two Namespace are equivalent
- * @access public
- * @return Boolean
- */
- equals: function(ns){
- return this.prefix === ns.prefix && this.uri === ns.uri;
- }
- }
- /**
- * @description QName class
- * @access public
- * @param uri {Namespace | String}
- * @param localName {String}
- */
- QName = function(uri, localName){
- var len = arguments.length;
- if(len >= 2){
- this.uri = String(uri);
- this._ns = (uri && uri.constructor == Namespace) ? uri : new Namespace(uri);
- this.localName = String(localName);
- }else if(len == 1){
- this.uri = "";
- this._ns = new Namespace();
- this.localName = String(uri);
- }else{
- this.uri = "";
- this._ns = new Namespace();
- this.localName = "";
- }
- }
- QName.prototype = {
- constructor: QName,
-
- /**
- * @description to string
- * @return String
- */
- toString: function(){
- var r = this.uri ? this.uri + "::" : "";
- return r +this.localName;
- },
- /**
- * @description return a QName copy object
- * @return QName
- */
- copy: function(){
- var qn = new QName();
- qn.uri = this.uri;
- qn.localName = this.localName;
- qn._ns = this._ns.copy();
- return qn;
- },
- /**
- * @description check if the two QName are equivalent
- * @access public
- * @return Boolean
- */
- equals: function(qname){
- return this.localName == qname.localName && this._ns.equals(qname._ns);
- }
- }
- /**
- * @description parse a name & value to a QName
- * @access internal
- * @static
- * @param name{String} namespace declaration name
- * @param value{String} namespace declaration value
- * @return QName
- */
- QName._format = function(name, value){
- var temp = name.split(":"), prefix, localName;
- if(temp.length==2){
- prefix = temp[0];
- localName = temp[1];
- }else{
- prefix = '';
- localName = name;
- }
- return new QName(new Namespace(prefix, value), localName);
- }
- /**
- * @description NodeKind class
- * @static
- */
- NodeKind = {
- 'ELEMENT': 'element',
- 'COMMENT': 'comment',
- 'PROCESSING_INSTRUCTIONS': 'processing-instructions',
- 'TEXT': 'text',
- 'ATTRIBUTE': 'attribute'
- }
-
- /**
- * @description get a suitable class for XML operations by the XMLList.
- * if the list contains only one child, then return the child XML.
- * @return XML|XMLList
- */
- _getXMLIfLengthEqualOne = function(list){
- if(list._list && list.length() == 1){
- return _getXMLIfLengthEqualOne(list._list[0]);
- }
- return list;
- };
- /**
- * @description XMLList is a XML collection
- * @param null
- */
- XMLList= function(){
- this._list = [];
- }
- merge(XMLList.prototype, {
- constructor: XMLList,
-
- /**
- * @description add a xml to the list
- * @access private
- * @return XMLList
- */
- _addXML: function(xml){
- if(xml.constructor == XML){
- this._list.push(xml);
- }else if(xml.constructor == XMLList){
- this._list = this._list.concat(xml._list);
- }
- return this;
- },
- /**
- * @description get the list length
- * @access public
- * @return int
- */
- length: function(){
- return this._list.length;
- },
- /**
- * @description you cannot call this method in a list, only XML owns childIndex method.
- * @access none
- * @return void
- */
- childIndex: function(){
- throw new Error("this method only availabe in single list XML");
- },
- /**
- * @description return all the child by localName in this xml list.
- * @access public
- * @return XMLList | XML
- */
- child: function(p){
- var list = new XMLList();
- this.each(function(item){
- var child = item.child(p);
- if(child.length()){
- list._addXML(child);
- }
- });
- return _getXMLIfLengthEqualOne(list);
- },
- /**
- * @description return all the child in this xml list.
- * @access public
- * @return XMLList | XML
- */
- children: function(){
- return this.child('*');
- },
- /**
- * @description return a special attribute type child by parameter
- * @access public
- * @param p{String} if the p is '*', return all attributes
- * @return XML | XMLList
- * @see attributes
- */
- attribute: function(p){
- var list = new XMLList();
- this.each(function(item){
- list._addXML(item.attribute(p));
- });
- return _getXMLIfLengthEqualOne(list);
- },
- /**
- * @description return all attribute type child.
- * @access public
- * @return XML | XMLList
- * @see attribute
- */
- attributes: function(p){
- return this.attribute('*');
- },
- /**
- * @description find special elements child from the XMLList tree top.
- * @access public
- * @param p{String} the element localName, if the localName is '*', return all the element child.
- * @return XML | XMLList
- */
- elements: function(p){
- var list = new XMLList();
- this.each(function(item){
- list._addXML(item.elements(p));
- });
- return _getXMLIfLengthEqualOne(list);
- },
- /**
- * @description find descendants child from the XMLList tree top.
- * @access public
- * @param p{String} the descendant localName, if the localName is '*', return all the descendants.
- * @return XML | XMLList
- */
- descendants: function(p){
- var list = new XMLList();
- this.each(function(item){
- list._addXML(item.descendants(p));
- });
- return _getXMLIfLengthEqualOne(list);
- },
- /**
- * @description merge multi text childs nearby to one text child of each list item.
- * @access public
- * @return void
- */
- normalize: function(){
- this.each(function(item){
- item.normalize();
- });
- },
- /**
- * @description check if all the list item owns simple content only
- * @access public
- * @return Boolean
- * @see hasComplexContent
- */
- hasSimpleContent: function(){
- for(var i=0, l = this._list.length; i < l; i++){
- var item = this._list[i];
- if(item.constructor == XMLList ||
- item.hasComplexContent()){
- return false;
- }
- }
- return true;
- },
- /**
- * @description check if all the list item owns simple content only
- * @access public
- * @return Boolean
- * @see hasSimpleContent
- */
- hasComplexContent: function(){
- return !this.hasSimpleContent();
- },
- /**
- * @description return the text type child
- * @access public
- * @return XML
- */
- text: function(){
- var xml = new XMLList();
- this.each(function(item){
- if(item.constructor == XML){
- var t = item.text();
- if(t._text != ""){
- xml._addXML(t);
- }
- }
- });
- return _getXMLIfLengthEqualOne(xml);
- },
- /**
- * @description return the comment type child
- * @access public
- * @return XML | XMLList
- */
- comments: function(){
- var xml = new XMLList();
- this.each(function(item){
- if(item.constructor == XML){
- xml._addXML(item.comments());
- }
- });
- return _getXMLIfLengthEqualOne(xml);
- },
- /**
- * @description return the XML processing-instructions.
- * @access public
- * @return XMLList | XML
- */
- processingInstructions: function(){
- var xml = new XMLList();
- this.each(function(item){
- if(item.constructor == XML){
- xml._addXML(item.processingInstructions());
- }
- });
- return _getXMLIfLengthEqualOne(xml);
- },
- /**
- * @description return an XMLList copy object.
- * @access public
- * @return XMLList
- */
- copy: function(){
- var list = new XMLList();
- this.each(function(item, i){
- list._list[i] = item.copy();
- });
- return list;
- },
- /**
- * @description return toXMLString of all the list item
- * @access public
- * @return String
- */
- toXMLString: function(){
- var s = [];
- this.each(function(item){
- s.push(item.toXMLString());
- });
- return s.join("\n");
- },
- /**
- * @description return toString of all the list item.
- * @access public
- * @return String
- */
- toString: function(){
- var s = "";
- this.each(function(item){
- s += item.toString();
- });
- return s;
- },
- //===================extension for javascript=================
- /**
- * @description return a special item by item index.
- * @access public
- * @param n{int} the item index
- * @return XML
- */
- item: function(n){
- return this._list[n];
- },
- /**
- * @description for loop the list item.
- * @access public
- * @param func{Function} the callback handler
- * @return void
- */
- each: function(func){
- for(var i = 0, l = this._list.length; i <l; i++){
- func(this._list[i], i, this);
- }
- }
- });
- /**
- * @description XML class
- * @param str{String}
- */
- XML = function(str){
- this._children = [];
- this._attributes = [];
- this._namespaces = [];
- this._nodeKind = NodeKind.ELEMENT;
- this._qname = null;
- this._parent = null;
- this._text = null;
- this._useCDATA = false;
-
- var current, self= this;
- if(str){
- _parseXML(str, {
- start: function(tag, attrs, unary ){
- var xml;
- if(!current){
- xml = self;
- }else{
- xml = new XML();
- xml._parent = current;
- }
- xml._qname = QName._format(tag);
- for(var i in attrs){
- var attr = new XML();
- attr._nodeKind = NodeKind.ATTRIBUTE;
- var _qname;
- if(attrs[i].name === 'xmlns'){
- _qname = new QName(new Namespace('xmlns', attrs[i].value), '');
- }else{
- _qname = QName._format(attrs[i].name, attrs[i].value);
- }
- var prefix = _qname._ns.prefix || "";
-
- if(prefix === 'xmlns'){
- var ns = new Namespace(_qname.localName, _qname.uri);
- xml.addNamespace(ns);
- if(_qname.localName == xml._qname._ns.prefix){
- xml.setNamespace(ns);
- }
- }else{
- attr._qname = _qname;
- attr._text = attrs[i].value;
- xml._attributes.push(attr);
- }
- }
- current = xml;
- if(unary){
- this.end(tag);
- }
- },
- chars: function(text, useCDATA){
- text = trim(text);
- if(text == "" && XML.ignoreWhitespace){
- return;
- }
- var el = new XML();
- el._nodeKind = NodeKind.TEXT;
- el._text = text;
- el._useCDATA = useCDATA;
- current._children.push(el);
- },
- end: function(tag){
- if(current && current._parent){
- current._parent._children.push(current);
- current = current._parent;
- }else if(current == self){
- current = null;
- }
- },
- comment: function(value){
- var el = new XML();
- el._nodeKind = NodeKind.COMMENT;
- el._text = value;
- current && current._children.push(el);
- },
- instruction: function(value){
- var el = new XML();
- el._nodeKind = NodeKind.PROCESSING_INSTRUCTIONS;
- el._text = value;
- current && current._children.push(el);
- }
- });
- }
- }
-
- merge(XML.prototype, {
- /**
- * @description add new namespace to this XML
- * @access public
- * @param ns{Namespace}
- * @return void
- */
- addNamespace: function(ns){
- if(ns.prefix !=undefined){
- this.removeNamespace(ns);
- this._namespaces.push(ns);
- }
- },
- /**
- * @description remove a namespace from this XML
- * @access public
- * @param ns{Namespace}
- * @return void
- */
- removeNamespace: function(ns){
- for(var i = 0, l = this._namespaces.length; i < l; i++){
- if(ns.prefix==this._namespaces[i].prefix){
- this._namespaces.splice(i, 1);
- break;
- }
- }
- },
- /**
- * @description reture a namespace by prefix
- * @access public
- * @param prefix{String}
- * @return Namespace
- */
- namespace: function(prefix){
- if(!prefix){
- return new Namespace();
- }
- for(var i = 0, l = this._namespaces.length; i < l; i++){
- if(prefix==this._namespaces[i].prefix){
- return this._namespaces[i];
- }
- }
- return undefined;
- },
- /**
- * @description set the namespace for this XML
- * @access public
- * @param ns{Namespace}
- * @return void
- */
- setNamespace: function(ns){
- if(ns && ns.constructor == Namespace){
- this.addNamespace(ns);
- if(this._qname){
- this._qname.uri = ns.uri;
- this._qname._ns = ns;
- }
- }
- },
- /**
- * @description return declarated namespace of this XML
- * @access public
- * @return Array
- */
- namespaceDeclarations: function(){
- return this._namespaces;
- },
- /**
- * @description return declarated namespace of this XML and all parent XML.
- * @access public
- * @return Array
- */
- inScopeNamespaces: function(){
- var array = this._namespaces;
- var chain = this._parent;
- while(chain){
- array = chain.inScopeNamespaces().concat(array);
- chain = chain._parent;
- }
- return array;
- },
- /**
- * @description return the nodekind of this element
- * @access public
- * @return String
- * @see NodeKind
- */
- nodeKind: function(){
- return this._nodeKind;
- },
- /**
- * @description return the full name (with declarated namespace) of this xml
- * @access public
- * @return String
- * @see localName
- */
- name: function(){
- if(!this._qname){
- return null;
- }
- if(this._qname.uri){
- return this._qname.uri +":"+this._qname.localName;
- }
- return this._qname.localName;
- },
- /**
- * @description return the local name (without declarated namespace) of this xml
- * @access public
- * @return String
- * @see name
- */
- localName: function(){
- if(!this._qname){
- return null;
- }
- return this._qname.localName;
- },
- /**
- * @description set the full name (with declarated namespace) of this xml
- * @access public
- * @return void
- * @see name
- */
- setName: function(name){
- if(this._qname == null){
- return;
- }
- if(/^[a-zA-Z]+[a-zA-Z0-9]*$/.test(name)){
- this._qname.uri = "";
- this._qname.localName = name;
- }else{
- throw new Error("invalid value for XML name");
- }
- },
- /**
- * @description set the local name (without declarated namespace) of this xml
- * @access public
- * @return void
- * @see localName
- */
- setLocalName: function(name){
- if(this._qname == null){
- return;
- }
- if(/^[a-zA-Z\$_]+[a-zA-Z0-9\$\-_]*$/.test(name)){
- this._qname.localName = name;
- }else{
- throw new Error("invalid value for XML localName");
- }
- },
- /**
- * @description get the length of this xml tree, return 1 always for XML.
- * @access public
- * @return int
- */
- length: function(){
- return 1;
- },
- /**
- * @description return a special attribute type child by param
- * @access public
- * @param p{String} if the p is '*', return all attributes
- * @return XML | XMLList
- * @see attributes
- */
- attribute: function(p){
- var attributes = this._attributes,
- i,
- l,
- item,
- list = new XMLList();
- for( i =0, l = attributes.length; i <l; i++){
- item = attributes[i];
- if(item._qname.localName == p || p == '*'){
- list._addXML(item);
- }
- }
- return _getXMLIfLengthEqualOne(list);
- },
- /**
- * @description return all attribute type child.
- * @access public
- * @return XML | XMLList
- * @see attribute
- */
- attributes: function(){
- return this.attribute('*');
- },
- /**
- * @description create a text type XML node by the text parameter,
- * if the text contains special characters, use CDATA tag.
- * @access private
- * @param text{String}
- * @return XML
- */
- _createTextNode: function(text){
- var el = new XML();
- el._nodeKind = NodeKind.TEXT;
- el._text = text;
- el._useCDATA =/['"<>&]/.test(text);
- return el;
- },
- /**
- * @description append child to the children list
- * @access public
- * @param child{XML | XMLList | String} the child need to be add
- * @return XML
- * @see prependChild
- */
- appendChild: function(child){
- var cc = child.constructor;
- if(cc == XML){
- child._parent = this;
- this._children.push(child);
- }else if(cc == XMLList){
- child.each(function(item){
- item._parent = this;
- });
- this._children = this._children.concat(child._list);
- }else if(cc == String){
- var c = this._createTextNode(child);
- c._parent = this;
- this._children.push(c);
- }
- return this;
- },
- /**
- * @description prepend child to the children list
- * @access public
- * @param child{XML | XMLList | String} the child need to be add
- * @return XML
- * @see appendChild
- */
- prependChild: function(child){
- var cc = child.constructor;
- if(cc == XML){
- child._parent = this;
- this._children.unshift(child);
- }else if(cc == XMLList){
- child.each(function(item){
- item._parent = this;
- });
- this._children = this._list.concat(this._children);
- }else if(cc === String){
- var c = this._createTextNode(child);
- c._parent = this;
- this._children.unshift(c);
- }
- return this;
- },
- /**
- * @description merge multi text childs nearby to one text child.
- * @access public
- * @return void
- */
- normalize: function(){
- var i,
- l,
- preTextEl,
- _c = this._children,
- newChildren = [];
-
- for(i = 0, l = _c.length; i < l; i++){
- var item = _c[i],
- nk = item.nodeKind();
- if(nk == NodeKind.TEXT){
- if(preTextEl){
- item._text = preTextEl._text + item._text;
- _c[i-1] = null;
- }
- preTextEl = item;
- }else if(nk == NodeKind.ELEMENT){
- item.normalize();
- preTextEl = null;
- }
- }
- for(i = 0, l = _c.length; i < l; i++){
- _c[i] && newChildren.push(_c[i]);
- }
- this._children = newChildren;
- },
- /**
- * @description return a filter children list, if the ignoreComments is true, the list will
- * not contains any comment child, same as processing-instructions child.
- * @access private
- * @return Array
- */
- _getFilterChildren: function(){
- var i,
- l,
- c = [],
- _c = this._children;
-
- for(i = 0, l = _c.length; i < l; i++){
- var item = _c[i],
- nk = item.nodeKind();
- if(nk == NodeKind.ELEMENT || nk == NodeKind.TEXT ||
- (nk == NodeKind.COMMENT && !XML.ignoreComments) ||
- (nk == NodeKind.PROCESSING_INSTRUCTIONS && !XML.ignoreProcessingInstructions)){
- c.push(item);
- }
- }
- return c;
- },
- /**
- * @description find a child by localName
- * @access public
- * @param p{String} the child localName, if the localName is '*', return all the child.
- * @return XML | XMLList
- */
- child: function(p){
- var list = new XMLList(),
- i,
- l,
- c = this._getFilterChildren();
- if(typeof p == 'number'){
- if(c.length != 0 && c[p]){
- list._addXML(c[p]);
- }
- }else{
- for(i=0, l=c.length; i < l;i++){
- var xml = c[i];
- if(xml.localName() == p || p=="*"){
- list._addXML(xml);
- }
- }
- }
-
- return _getXMLIfLengthEqualOne(list);
- },
- /**
- * @description return the child index in its parent child list, return -1 if it is a root XML.
- * @access public
- * @return int
- */
- childIndex: function(p){
- if(this._parent){
- return arrayIndexOf(this._parent._getFilterChildren(), this);
- }
- return -1;
- },
- /**
- * @description return all the child
- * @access public
- * @return XML | XMLList
- */
- children: function(){
- return this.child("*");
- },
- /**
- * @description set the child content
- * @access public
- * @param child{string | XML | XMLList} the child need to be replaced
- * @return XML
- */
- setChildren: function(child){
- this._children = [];
- return this.appendChild(child);
- },
- /**
- * @description replace a child by new content.
- * @access public
- * @param a{string} the child need to be replaced
- * @param b{String | XML | XMLList} the new content
- * @return XML
- */
- replace: function(a, b){
- var replacedIndex = -1,
- i,
- l,
- c = this._children,
- newChildren = [];
-
- for(i=0, l=c.length; i < l; i++){
- var xml = c[i], nk = xml.nodeKind();
- if((xml.localName() == a || a=="*") && nk == NodeKind.ELEMENT){
- if(replacedIndex == -1){
- replacedIndex = i;
- var cc = b.constructor;
- if(cc == XML){
- b._parent = this;
- newChildren.push(b);
- }else if(cc == XMLList){
- b.each(function(item){
- item._parent= this;
- });
- newChildren = newChildren.concat(b._list);
- }else if(cc === String){
- var t= this._createTextNode(b);
- t._parent = this;
- newChildren.push(t);
- }
- }
- }else{
- newChildren.push(xml);
- }
- }
- if(replacedIndex != -1){
- this._children = newChildren;
- this.normalize();
- }
- return this;
- },
- /**
- * @description find element type child.
- * @access public
- * @param p{String} the child localName, if the localName is '*', return all the element type child.
- * @return XML | XMLList
- */
- elements: function(p){
- if(arguments.length == 0){
- p = '*';
- }
- var list = new XMLList(),
- i,
- l,
- c = this._children;
-
- for(i=0, l=c.length; i < l;i++){
- var xml = c[i];
- if((xml.localName() == p || p=='*') && xml.nodeKind() == NodeKind.ELEMENT){
- list._addXML(xml);
- }
- }
- return _getXMLIfLengthEqualOne(list);
- },
- /**
- * @description find descendants child from the XML tree top.
- * @access public
- * @param p{String} the descendant localName, if the localName is '*', return all the descendants.
- * @return XML | XMLList
- */
- descendants: function(p){
- if(arguments.length == 0){
- p = '*';
- }
- var list = new XMLList(),
- i,
- l,
- c = this._children;
-
- for(i=0, l=c.length; i < l;i++){
- var xml = c[i], nk = xml.nodeKind();
- if((xml.localName() == p || p=='*') && (nk==NodeKind.ELEMENT || nk == NodeKind.TEXT)){
- list._addXML(xml);
- }
- if(xml._nodeKind == NodeKind.ELEMENT){
- list._addXML(xml.descendants(p));
- }
- }
- return _getXMLIfLengthEqualOne(list);
- },
- /**
- * @description insert a child after the special child.
- * @access public
- * @param child1{XML | XMLList} the child in XML
- * @param child2{XML | XMLList} the child need to be inserted.
- * @return XML
- * @see insertChildAfter
- */
- insertChildBefore: function(child1, child2){
- if(child1 == null){
- return this.appendChild(child2);
- }
- if(child1.constructor != XML){
- return undefined;
- }
- var cc = child1.childIndex();
- if(child1._parent == this && cc != -1){
- if(child2.constructor == XML){
- child2._parent = this;
- this._children.splice(cc, 0, child2);
- }else if(child2.constructor == XMLList){
- for(var i = 0, l = child2._list.length; i < l; i++){
- child2._list[i]._parent = this;
- this._children.splice(cc+i, 0, child2._list[i]);
- }
- }else{
- return undefined;
- }
- return this;
- }else{
- return undefined;
- }
- },
- /**
- * @description insert a child before the special child.
- * @access public
- * @param child1{XML | XMLList} the child in XML
- * @param child2{XML | XMLList} the child need to be inserted.
- * @return XML
- * @see insertChildBefore
- */
- insertChildAfter: function(child1, child2){
- if(child1 == null){
- return this.prependChild(child2);
- }
- if(child1.constructor != XML){
- return undefined;
- }
- var cc = child1.childIndex();
- if(child1._parent == this && cc != -1){
- if(child2.constructor == XML){
- child2._parent = this;
- this._children.splice(cc+1, 0, child2);
- }else if(child2.constructor == XMLList){
- for(var i = 0, l = child2._list.length; i < l; i++){
- child2._list[i]._parent = this;
- this._children.splice(cc+1+i, 0, child2._list[i]);
- }
- }else{
- return undefined;
- }
- return this;
- }else{
- return undefined;
- }
- },
- /**
- * @description return the parent XML.
- * @access public
- * @return XML
- */
- parent: function(){
- return this._parent;
- },
- /**
- * @description check if the XML contains element type child, If has return false.
- * @acess public
- * @return Boolean
- * @see hasComplexContent
- */
- hasSimpleContent: function(){
- var c = this._children;
- for(var i=0, l = c.length; i<l; i++){
- var nk = c[i].nodeKind();
- if(nk === NodeKind.ELEMENT){
- return false;
- }
- }
- return true;
- },
- /**
- * @description check if the XML contains element type child, If has return true.
- * @access public
- * @return Boolean
- * @see hasSimpleContent
- */
- hasComplexContent: function(){
- return !this.hasSimpleContent();
- },
- /**
- * @description return the comment type child
- * @access public
- * @return XML | XMLList
- */
- comments: function(){
- var list = new XMLList(),
- i,
- l,
- c = this._getFilterChildren();
-
- for(i=0, l=c.length; i < l;i++){
- var xml = c[i];
- if(xml.nodeKind() == NodeKind.COMMENT){
- list._addXML(xml);
- }
- }
- return _getXMLIfLengthEqualOne(list);
- },
- /**
- * @description return the text type child
- * @access public
- * @return XML
- */
- text: function(){
- var c = this._children,
- r = "";
- for(var i=0, l = c.length; i<l; i++){
- var nk = c[i].nodeKind();
- if(nk === NodeKind.TEXT){
- if(c[i]._useCDATA){
- r += c[i]._text;
- }else{
- r += replaceFromEntity(c[i]._text);
- }
- }
- }
- return this._createTextNode(r);
- },
- /**
- * @description return the XML comments.
- * @access public
- * @return XMLList | XML
- */
- comments: function(){
- var list = new XMLList(),
- i,
- l,
- c = this._getFilterChildren();
-
- for(i=0, l=c.length; i < l;i++){
-
- var xml = c[i];
- if(xml.nodeKind && xml.nodeKind() == NodeKind.COMMENT){
- list._addXML(xml);
- }
- }
- return _getXMLIfLengthEqualOne(list);
- },
- /**
- * @description return the XML processing-instructions.
- * @access public
- * @return XMLList | XML
- */
- processingInstructions: function(){
- var list = new XMLList(),
- i,
- l,
- c = this._getFilterChildren();
-
- for(i=0, l=c.length; i < l;i++){
-
- var xml = c[i];
- if(xml.nodeKind && xml.nodeKind() == NodeKind.PROCESSING_INSTRUCTIONS){
- list._addXML(xml);
- }
- }
- return _getXMLIfLengthEqualOne(list);
- },
- /**
- * @description return an XML copy
- * @access public
- * @return XML
- */
- copy: function(){
- var xml = new XML(),
- i,
- l;
- xml._nodeKind = this._nodeKind;
- xml._text = this._text;
- xml._useCDATA = this._useCDATA;
- if(this._qname){
- xml._qname = this._qname.copy();
- }
- for(i=0, l = this._namespaces.length; i < l; i++){
- xml._namespaces[i] = this._namespaces[i].copy();
- }
- for(i = 0, l = this._attributes.length; i <l; i++){
- xml._attributes[i] = this._attributes[i].copy();
- }
- for(i = 0, l = this._children.length; i <l; i++){
- xml._children[i] = this._children[i].copy();
- }
- return xml;
- },
- /**
- * @description format the XML to a String
- * @param indent{int} the whitespace indent
- * @access private
- */
- _toXMLString: function(indent, scopeNamespace){
- var s = "",
- tag,
- i,
- l,
- nk = this._nodeKind,
- ns = scopeNamespace ? this.inScopeNamespaces() : this._namespaces,
- attrs = this._attributes,
- children = this._children,
- prettyPrinting = XML.prettyPrinting,
- p = [];
- indent = indent || 0;
-
- if(prettyPrinting){
- for(i = 0; i< indent; i++){
- s +=" ";
- }
- }
- if(nk == NodeKind.ATTRIBUTE){
- return s + this._text;
- }else if(nk == NodeKind.TEXT){
- if(this._useCDATA){
- return s + "<![CDATA["+this._text+"]]>";
- }else{
- return s + replaceToEntity(this._text);
- }
- }else if(nk == NodeKind.COMMENT){
- return s + "<!--"+this._text +"-->";
- }else if(nk == NodeKind.PROCESSING_INSTRUCTIONS){
- return s + "<?" + this._text + "?>";
- }
-
- if(this._qname._ns.prefix){
- tag = this._qname._ns.prefix+":" +this.localName();
- }else{
- tag = this.localName();
- }
-
- s += "<"+tag;
- for(i = 0, l = ns.length; i <l; i++){
- var prefix = ns[i].prefix ? 'xmlns:'+ns[i].prefix : 'xmlns';
- p.push({label: prefix, value:ns[i].uri});
- }
- for(i = 0, l = attrs.length; i <l; i++){
- var q = attrs[i]._qname,
- prefix = q._ns.prefix,
- label;
- if(prefix){
- label =prefix+ ':'+q.localName;
- }else{
- label = q.localName;
- }
- p.push({label:label, value:attrs[i]._text});
- }
- if(p.length>0){
- for(i=0, l=p.length; i<l; i++){
- s += " "+p[i].label+"=\""+p[i].value+"\"";
- }
- }
- p = [];
- for(i = 0, l = children.length; i < l; i++){
- var el = children[i];
- if(el.nodeKind() == NodeKind.ELEMENT){
- p.push(el);
- }else if(el.nodeKind() == NodeKind.COMMENT && !XML.ignoreComments){
- p.push(el);
- }else if(el.nodeKind() == NodeKind.PROCESSING_INSTRUCTIONS && !XML.ignoreProcessingInstructions){
- p.push(el);
- }else if(el.nodeKind() == NodeKind.TEXT){
- p.push(el);
- }
- }
- if(p.length == 0){
- s += "/>";
- }else if(p.length == 1 && p[0].nodeKind() == NodeKind.TEXT){
- s += ">";
- s += p[0]._toXMLString(0);
- s += "</"+tag+">";
- }else{
- s += ">";
- for(i = 0, l= p.length; i<l; i++){
- if(prettyPrinting){
- s += "\n";
- }
- s += p[i]._toXMLString(indent+XML.prettyIndent);
- }
- if(prettyPrinting){
- s += "\n";
- for(i = 0; i< indent; i++){
- s += " ";
- }
- }
- s += "</"+tag+">";
- }
- return s;
- },
- /**
- * @description return the XML string
- * @access public
- * @return String
- */
- toXMLString: function(){
- return this._toXMLString(0, true);
- },
- /**
- * @description return a string representation. If it contains complex content, return the toXMLString.
- * @access public
- * @return String
- */
- toString: function(){
- if(this.hasComplexContent()){
- return this.toXMLString();
- }
- if(this.nodeKind() == NodeKind.TEXT || this.nodeKind() == NodeKind.ATTRIBUTE){
- return this._text;
- }
- var s = "";
- for(var i = 0, l = this._children.length; i < l; i++){
- var el = this._children[i];
- if(el._nodeKind == NodeKind.TEXT){
- if(el._useCDATA){
- s += el._text;
- }else{
- s += replaceFromEntity(el._text);
- }
- }
- }
- return s;
- },
- //================extension for javascript=========================
- /**
- * @description get the XML simple node value
- * @access public
- * @return String
- * @see setValue
- */
- getValue: function(){
- var nk = this._nodeKind;
- if(nk == NodeKind.TEXT){
- if(!this._useCDATA && containsEntity(this._text)){
- return replaceFromEntity(this._text);
- }
- return this._text;
- }else if(nk == NodeKind.ATTRIBUTE){
- return this._text;
- }else if(nk == NodeKind.ELEMENT && this.hasSimpleContent()){
- var t = this.text();
- if(t.getValue){
- return t.getValue();
- }
- }
- return undefined;
- },
- /**
- * @description set the XML simple node value
- * @access public
- * @param val{String} the new node value
- * @return void
- * @see getValue
- */
- setValue: function(val){
- var nk = this._nodeKind;
- if(nk == NodeKind.TEXT || nk == NodeKind.ATTRIBUTE
- || nk == NodeKind.COMMENT || nk == NodeKind.PROCESSING_INSTRUCTIONS){
- this._text = val;
- }else if(nk == NodeKind.ELEMENT && this.hasSimpleContent()){
- var c = [],
- newText = this._createTextNode(val);
- newText._parent = this;
- c.push(newText);
- for(var i = 0, l = this._children.length; i < l; i++){
- var item = this._children[i];
- if(item._nodeKind != NodeKind.TEXT){
- c.push(item);
- }
- }
- this._children = c;
- }
- return this;
- }
- });
-
-
- /**
- * @description static properties and methods.
- */
- merge(XML, {
-
- ignoreComments: true,
- ignoreProcessingInstructions: true,
- ignoreWhitespace: true,
- prettyIndent: 2,
- prettyPrinting: true,
-
- /**
- * @description get an object copy indicating the XML setting.
- * @return Object
- */
- settings: function(){
- return {
- ignoreComments: this.ignoreComments,
- ignoreProcessingInstructions: this.ignoreProcessingInstructions,
- ignoreWhitespace: this.ignoreWhitespace,
- prettyIndent: this.prettyIndent,
- prettyPrinting: this.prettyPrinting
- }
- },
- /**
- * @description set the XML setting
- * @param sett{Object}
- * @return void
- */
- setSettings: function(sett){
- if(!sett){ return }
- var assign = function(p){
- if(sett.hasOwnProperty(p)){
- XML[p] = sett[p];
- }
- }
- assign("ignoreComments");
- assign("ignoreProcessingInstructions");
- assign("ignoreWhitespace");
- assign("prettyIndent");
- assign("prettyPrinting");
- }
- });
-
- /**
- * @description return global object jsxml
- * @return Object
- */
- return {
- containsEntity: containsEntity,
- replaceToEntity: replaceToEntity,
- replaceFromEntity: replaceFromEntity,
- parseXML: _parseXML,
- Namespace: Namespace,
- QName: QName,
- NodeKind: NodeKind,
- XMLList: XMLList,
- XML: XML
- }
-})();
View
330 examples/d2forum.html 100755 → 100644
@@ -1,166 +1,166 @@
-<!doctype>
-<html>
-<head>
-<meta charset="utf-8">
-<title>jsxml example - D2 forum</title>
-<link href="http://k.kbcdn.com/min/f=/k2/css/reset-1-0-0.css,/k2/css/color-1-0-2.css,/k2/css/common-1-0-1.css,/k2/css/grids-1-0-0.css" type="text/css" rel="stylesheet">
-</head>
-<style>
-#container{
- text-align:left;
-}
-#container img,
-#container .summary{
- float:left;
- margin-right:10px;
-}
-#container .summary{
- width: 650px;
-}
-#container .info{
- padding-top:4px;
- font-size:11px;
-}
-#container .user{
- font-weight:bold;
-}
-#container .time{
- color:#999;
- margin-right:10px;
- font-weight:normal;
-}
-#container li{
- border-top:#999 1px dashed;
- padding:5px 0;
- *zoom:1;
-}
-#container li:after{
- content:"\0020";
- display:block;
- height:0;
- clear:both
-}
-#load-tweets{
- -webkit-box-shadow: inset 0 0 1px rgba(0, 0, 0, 0.1);
- -moz-box-shadow: inset 0 0 1px rgba(0, 0, 0, 0.1);
- box-shadow: inset 0 0 1px rgba(0, 0, 0, 0.1);
- -webkit-transition: all 0.1s ease;
- -moz-transition: all 0.1s ease;
- -o-transition: all 0.1s ease;
- line-height: 1.2;
- background-color: #49A7F3;
- display: inline-block;
- padding: 12px 20px !important;
- -webkit-border-radius: 12px;
- -moz-border-radius: 12px;
- border-radius: 4px;
- color: white !important;
- text-decoration: none;
- border: none !important;
- font-size: 22px;
- font-weight: bold;
- margin:5px 0 10px 0;
- width:726px;
-}
-#load-tweets:hover {
- background-color: #82c7ff;
-}
-#load-tweets:active {
- -webkit-box-shadow: inset 0 0 8px rgba(0, 0, 0, 0.6);
- -moz-box-shadow: inset 0 0 8px rgba(0, 0, 0, 0.6);
- box-shadow: inset 0 0 8px rgba(0, 0, 0, 0.6);
-}
-</style>
-<body>
-<div class="k2-single" style="width:728px">
- <h1><a href="http://www.d2forum.org/d2/6/" target="_blank"><img src="http://img03.taobaocdn.com/tps/i3/T1i6WgXgNiXXXXXXXX-728-90.jpg" width="728" height="90" alt="第六届 D2前端技术论坛 (7月9日·杭州)" /></a></h1>
- <div><button id="load-tweets" href="#">搜索微博</button></div>
- <div id="container"></div>
-</div>
-<script src="http://k.kbcdn.com/k2/seed/seed-1-3-12.js"></script>
-<script src="../src/jsxml.js"></script>
-<script>
-Date.prototype.pattern=function(fmt) {
- var o = {
- "M+" : this.getMonth()+1, //月份
- "d+" : this.getDate(), //日
- "h+" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, //小时
- "H+" : this.getHours(), //小时
- "m+" : this.getMinutes(), //分
- "s+" : this.getSeconds(), //秒
- "q+" : Math.floor((this.getMonth()+3)/3), //季度
- "S" : this.getMilliseconds() //毫秒
- };
- var week = {
- "0" : "\u65e5",
- "1" : "\u4e00",
- "2" : "\u4e8c",
- "3" : "\u4e09",
- "4" : "\u56db",
- "5" : "\u4e94",
- "6" : "\u516d"
- };
- if(/(y+)/.test(fmt)){
- fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
- }
- if(/(E+)/.test(fmt)){
- fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "\u661f\u671f" : "\u5468") : "")+week[this.getDay()+""]);
- }
- for(var k in o){
- if(new RegExp("("+ k +")").test(fmt)){
- fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
- }
- }
- return fmt;
-}
-
-
-YUI().use('node-base', 'io-base', 'substitute', 'yql', function(Y){
- var XML = jsxml.XML,
- query = 'select * from xml where url="http://api.t.sina.com.cn/trends/statuses.xml?trend_name='+encodeURIComponent("D2前端技术论坛")+'&source=506163941"';
- var init = function(data){
- var xml = new XML(data),
- list = xml.child("status"),
- html = "",
- tpl = "<li><img src='{image_src}'/><div class='summary'><span class='user'><a href='{user_href}' target='_blank'>{user}</a></span>:<span class='text'>{text}</span><div class='info'><b class='time'>{time}</b>来自<span class='source'>{source}</span></div></div></li>";
-
- list.each(function(item){
- var date = new Date(item.child('created_at').getValue()),
- screenName = item.child('user').child('screen_name').getValue(),
- user_href = "http://weibo.com/n/"+screenName,
- text = item.child('text').getValue();
-
- text = text.replace(/(http:[^\s::()(),,。]+)/g, function(i){
- return '<a href="'+ i+'" target="_blank">'+i+'</a>';
- });
- text = text.replace(/@([^\s::()(),,.。]+)/g, function(i){
- var screenName = i.substr(1);
- return '<a href="http://weibo.com/n/' + screenName+'" target="_blank">@'+screenName+'</a>';
- });
-
- html += Y.substitute(tpl, {
- user:screenName,
- user_href: user_href,
- image_src: item.child('user').child('profile_image_url').getValue(),
- text: text,
- source: item.child('source').toXMLString(),
- time: date.pattern("yyyy-MM-dd hh:mm:ss")
- });
- });
- Y.one('#container').setContent('<ul>'+html+'</ul>');
- }
-
- //entry point
- Y.one("#load-tweets").on('click', function(){
- Y.one('#container').setContent("正在搜索...");
- Y.YQL(query, function(r){
- init(r.results[0]);
- }, {format:'xml'});
- });
-
-
-
-});
-</script>
-</body>
+<!doctype>
+<html>
+<head>
+<meta charset="utf-8">
+<title>jsxml example - D2 forum</title>
+<link href="http://k.kbcdn.com/min/f=/k2/css/reset-1-0-0.css,/k2/css/color-1-0-2.css,/k2/css/common-1-0-1.css,/k2/css/grids-1-0-0.css" type="text/css" rel="stylesheet">
+</head>
+<style>
+#container{
+ text-align:left;
+}
+#container img,
+#container .summary{
+ float:left;
+ margin-right:10px;
+}
+#container .summary{
+ width: 650px;
+}
+#container .info{
+ padding-top:4px;
+ font-size:11px;
+}
+#container .user{
+ font-weight:bold;
+}
+#container .time{
+ color:#999;
+ margin-right:10px;
+ font-weight:normal;
+}
+#container li{
+ border-top:#999 1px dashed;
+ padding:5px 0;
+ *zoom:1;
+}
+#container li:after{
+ content:"\0020";
+ display:block;
+ height:0;
+ clear:both
+}
+#load-tweets{
+ -webkit-box-shadow: inset 0 0 1px rgba(0, 0, 0, 0.1);
+ -moz-box-shadow: inset 0 0 1px rgba(0, 0, 0, 0.1);
+ box-shadow: inset 0 0 1px rgba(0, 0, 0, 0.1);
+ -webkit-transition: all 0.1s ease;
+ -moz-transition: all 0.1s ease;
+ -o-transition: all 0.1s ease;
+ line-height: 1.2;
+ background-color: #49A7F3;
+ display: inline-block;
+ padding: 12px 20px !important;
+ -webkit-border-radius: 12px;
+ -moz-border-radius: 12px;
+ border-radius: 4px;
+ color: white !important;
+ text-decoration: none;
+ border: none !important;
+ font-size: 22px;
+ font-weight: bold;
+ margin:5px 0 10px 0;
+ width:726px;
+}
+#load-tweets:hover {
+ background-color: #82c7ff;
+}
+#load-tweets:active {
+ -webkit-box-shadow: inset 0 0 8px rgba(0, 0, 0, 0.6);
+ -moz-box-shadow: inset 0 0 8px rgba(0, 0, 0, 0.6);
+ box-shadow: inset 0 0 8px rgba(0, 0, 0, 0.6);
+}
+</style>
+<body>
+<div class="k2-single" style="width:728px">
+ <h1><a href="http://www.d2forum.org/d2/6/" target="_blank"><img src="http://img03.taobaocdn.com/tps/i3/T1i6WgXgNiXXXXXXXX-728-90.jpg" width="728" height="90" alt="第六届 D2前端技术论坛 (7月9日·杭州)" /></a></h1>
+ <div><button id="load-tweets" href="#">搜索微博</button></div>
+ <div id="container"></div>
+</div>
+<script src="http://k.kbcdn.com/k2/seed/seed-1-3-12.js"></script>
+<script src="../src/jsxml.js"></script>
+<script>
+Date.prototype.pattern=function(fmt) {
+ var o = {
+ "M+" : this.getMonth()+1, //月份
+ "d+" : this.getDate(), //日
+ "h+" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, //小时
+ "H+" : this.getHours(), //小时
+ "m+" : this.getMinutes(), //分
+ "s+" : this.getSeconds(), //秒
+ "q+" : Math.floor((this.getMonth()+3)/3), //季度
+ "S" : this.getMilliseconds() //毫秒
+ };
+ var week = {
+ "0" : "\u65e5",
+ "1" : "\u4e00",
+ "2" : "\u4e8c",
+ "3" : "\u4e09",
+ "4" : "\u56db",
+ "5" : "\u4e94",
+ "6" : "\u516d"
+ };
+ if(/(y+)/.test(fmt)){
+ fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
+ }
+ if(/(E+)/.test(fmt)){
+ fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "\u661f\u671f" : "\u5468") : "")+week[this.getDay()+""]);
+ }
+ for(var k in o){
+ if(new RegExp("("+ k +")").test(fmt)){
+ fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
+ }
+ }
+ return fmt;
+}
+
+
+YUI().use('node-base', 'io-base', 'substitute', 'yql', function(Y){
+ var XML = jsxml.XML,
+ query = 'select * from xml where url="http://api.t.sina.com.cn/trends/statuses.xml?trend_name='+encodeURIComponent("D2前端技术论坛")+'&source=506163941"';
+ var init = function(data){
+ var xml = new XML(data),
+ list = xml.child("status"),
+ html = "",
+ tpl = "<li><img src='{image_src}'/><div class='summary'><span class='user'><a href='{user_href}' target='_blank'>{user}</a></span>:<span class='text'>{text}</span><div class='info'><b class='time'>{time}</b>来自<span class='source'>{source}</span></div></div></li>";
+
+ list.each(function(item){
+ var date = new Date(item.child('created_at').getValue()),
+ screenName = item.child('user').child('screen_name').getValue(),
+ user_href = "http://weibo.com/n/"+screenName,
+ text = item.child('text').getValue();
+
+ text = text.replace(/(http:[^\s::()(),,。]+)/g, function(i){
+ return '<a href="'+ i+'" target="_blank">'+i+'</a>';
+ });
+ text = text.replace(/@([^\s::()(),,.。]+)/g, function(i){
+ var screenName = i.substr(1);
+ return '<a href="http://weibo.com/n/' + screenName+'" target="_blank">@'+screenName+'</a>';
+ });
+
+ html += Y.substitute(tpl, {
+ user:screenName,
+ user_href: user_href,
+ image_src: item.child('user').child('profile_image_url').getValue(),
+ text: text,
+ source: item.child('source').toXMLString(),
+ time: date.pattern("yyyy-MM-dd hh:mm:ss")
+ });
+ });
+ Y.one('#container').setContent('<ul>'+html+'</ul>');
+ }
+
+ //entry point
+ Y.one("#load-tweets").on('click', function(){
+ Y.one('#container').setContent("正在搜索...");
+ Y.YQL(query, function(r){
+ init(r.results[0]);
+ }, {format:'xml'});
+ });
+
+
+
+});
+</script>
+</body>
</html>
View
148 examples/weather.html 100755 → 100644
@@ -1,75 +1,75 @@
-<!doctype>
-<html>
-<head>
-<meta charset="utf-8">
-<title>jsxml example - Yahoo weather</title>
-</head>
-<style>
-html{
- background:#f2f2f2;
-}
-body{
- padding-top:20px;
- width:960px;
- margin:0 auto;
- text-align:center;
- color:#404040;
- font-family: 'Microsoft Yahei', Verdana, Arial;
- text-shadow:#fff 1px 0px 1px;
-}
-
-ol{
- list-style:none;
-}
-
-#container{
- text-align:left;
-}
-</style>
-<body>
-<h1>jsxml example - Yahoo weather</h1>
-<button id="btn">fetch weather data</button>
-<div id="container">
-</div>
-<script src="http://cdnjs.cloudflare.com/ajax/libs/yui/3.3.0/yui-min.js"></script>
-<script src="../src/jsxml.js"></script>
-<script>
-YUI().use('node-base', 'yql', 'substitute', function(Y){
- //http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20location%3D'CHXX0044'
- var query = "select * from weather.forecast where location='CHXX0044'";
- var XML = jsxml.XML;
- var init = function(){
- var list = xml.descendants('forecast'),
- template = "{date},{day},天气{weather},最高气温{high},最低气温{low}。",
- innerHTML = '<h2>'+xml.child('item').child('title').getValue()+'</h1>';
-
- innerHTML += '<h3>天气预报</h3><ol>';
- list.each(function(item, index){
- var html = Y.substitute(template, {
- date: item.attribute('date').getValue(),
- day: item.attribute('day').getValue(),
- high: item.attribute('high').getValue(),
- low: item.attribute('low').getValue(),
- weather: item.attribute('text').getValue()
- });
- innerHTML += '<li>'+html +'</li>';
- });
- innerHTML += '</ol>';
- innerHTML += "<h3>详情</h3>";
- innerHTML += "<div>"+xml.child('item').child('description').getValue() + "</div>";
- Y.one('#container').setContent(innerHTML);
- };
- var getWeather = function(){
- Y.one('#container').setContent('start fetching weather data...');
- Y.YQL(query, function(r){
- xml = new XML(r.results[0]);
- init();
- }, {format:'xml'});
- }
- Y.one('#btn').on('click', function(e){
- getWeather();
- });
-});
-</script>
-</body>
+<!doctype>
+<html>
+<head>
+<meta charset="utf-8">
+<title>jsxml example - Yahoo weather</title>
+</head>
+<style>
+html{
+ background:#f2f2f2;
+}
+body{
+ padding-top:20px;
+ width:960px;
+ margin:0 auto;
+ text-align:center;
+ color:#404040;
+ font-family: 'Microsoft Yahei', Verdana, Arial;
+ text-shadow:#fff 1px 0px 1px;
+}
+
+ol{
+ list-style:none;
+}
+
+#container{
+ text-align:left;
+}
+</style>
+<body>
+<h1>jsxml example - Yahoo weather</h1>
+<button id="btn">fetch weather data</button>
+<div id="container">
+</div>
+<script src="http://cdnjs.cloudflare.com/ajax/libs/yui/3.3.0/yui-min.js"></script>
+<script src="../src/jsxml.js"></script>
+<script>
+YUI().use('node-base', 'yql', 'substitute', function(Y){
+ //http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20location%3D'CHXX0044'
+ var query = "select * from weather.forecast where location='CHXX0044'";
+ var XML = jsxml.XML;
+ var init = function(){
+ var list = xml.descendants('forecast'),
+ template = "{date},{day},天气{weather},最高气温{high},最低气温{low}。",
+ innerHTML = '<h2>'+xml.child('item').child('title').getValue()+'</h1>';
+
+ innerHTML += '<h3>天气预报</h3><ol>';
+ list.each(function(item, index){