E4X教程[5] - 全局 XML 对象

全局 XML 对象

E4X-capable JavaScript 引擎在全局对象上放了一个新的属性。XML 对象有许多属性允许你定制解析和序列化 E4X。XML 元素从他们创建开始就记住 XML 对象的设置。

扩展 XML.prototype

XML.prototype 和 XMLList.prototype(XMLList.prototype 实际上就是 XML.prototype)不能像其他构造器(例如 Object)一样扩展。你只能在 XML.prototype 里定义方法,而不能定义字段。要向 XML.prototype 添加一个方法,则要定义 XML.prototype.function::methodName 或 XML.prototype.funciton::[methodNameString]。下例定义 fooCount() 方法,返回 XML 中 元素的个数:

XML.prototype.function::fooCount = function fooCount() {
  return this..foo.length();
};
<foobar><foo/><foo/><foo/></foobar>.fooCount() // returns 3

ignoreComments

默认为 true。该属性告诉 E4X 在序列化和筛选时忽略注释节点。即当 ignoreComments 为 ture 时 .comments() 返回空。观察如下例子:

var element = <foo>
                <!-- my comment -->
                <bar/>
              </foo>;
element.comments().length(); // returns 0
element.toXMLString(); // returns <foo><bar/></foo>
XML.ignoreComments = false;
element = <foo>
            <!-- my comment -->
            <bar/>
          </foo>;
element.comments().length(); // returns 1
element.toXMLString(); // returns <foo><!-- my comment --><bar/></foo>

ignoreProcessingInstructions

默认为 ture。该属性告诉 E4X 在序列化和筛选时忽略 XML 中的处理指令。例如:

var element = <foo>
                <?process x="true"?>
                <bar/>
                <?process x="false"?>
              </foo>;
element.toXMLString();
// returns <foo><bar/></foo>

XML.ignoreProcessingInstructions = false;
var element = <foo>
                <?process x="true"?>
                <bar/>
                <?process x="false"?>
              </foo>;
element.toXMLString();
// returns <foo><?process x="true"?><bar/><?process x="false"?></foo>

ignoreWhitespace

默认为 true。忽略节点之间以及节点文本头尾两端的空白,而其他的则被解析为文本节点或作为文本节点的一部分。

prettyPrinting

默认是 true。为 true 时,toXMLString() 序列化 E4X 对象时会包含换行和缩进。

prettyIndent

默认值是 2。代表 XML 树每层缩进的空格数。如果 prettyPrinting 是 false 则忽略。

redraimentE4X