`
hereson
  • 浏览: 1450012 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

e4x - 对xml操作的一些示例

阅读更多

as3终于给了xml一个名分,使他成了真正的内置数据类型,

现在我们不必像以前一样,把xml转成数组或者object了,直接可以操作xml了

以下copy自as3 cookbook 第20章

写xml操作:

var example:XML = <abc><a>eh</a><b>bee</b><c>see</c></abc>;

用变量写:

// Assume two variables exist, username and score
var username:String = "Darron";
var score:int = 1000;

// Use curly braces around the variable name to use its value when
// assigning XML via an XML literal
var example:XML = <gamescore>
 <username>{username}</username>
 <score>{score}</score>
 </gamescore>;

字符串:

// Create the XML structure with a string so use the value of both
// username and score inside of the XML packet.
var str:String = "<gamescore><username>" + username + "</username>"
 + "<score>" + score + "</score></gamescore>";

// Pass the string to the constructor to create an XML object
var example:XML = new XML( str );

填加元素

// Create an XML instance to add elements to
var example:XML = <example />;

// Create a new XML node named newElement and add it to the
// example instance
example.newElement = <newElement />;

/* Displays:
 <example>
 <newElement/>
 </example>
*/
trace( example );

技巧:

// Create an XML instance to work with
var example:XML = <example />;

var id:int = 10;

// Create a string to incorporate the value of id in the node name
example[ "user" + id ] = "";

/* Displays:
 <example>
 <user10/>
 </example>
*/
trace( example );

“-” 会引起编译器错误,用数组操作符避免这个

example.some-element = ""; // Generates a compiler error

example[ "some-element" ] = "";

insertChildBefore 和 insertChildAfter 作用

// Create an XML instance to work with
var example:XML = <example/>;

// Create an empty two element node
example.two = "";

// Before the two element node, add a one element node
example = example.insertChildBefore( example.two, <one /> );

// After the two element node, add a three element node
example = example.insertChildAfter( example.two, <three /> );

/* Displays:
<example>
 <one/>
 <two/>
 <three/>
</example>
*/
trace( example );

填加 文本节点 到xmlobject:

// Create an XML instance to work with
var example:XML = <example/>;

// Create a text node from a string
example.firstname = "Darron";

// Create a text node from a number
example.number = 24.9;

// Create a text node from a boolean
example.boolean = true;

// Create a text node from an array
example.abc = ["a", undefined, "b", "c", null, 7, false];

/* Displays:
<example>
 <firstname>Darron</firstname>
 <number>24.9</number>
 <boolean>true</boolean>
 <abc>a,,b,c,,7,false</abc>
</example>
*/
trace( example );

appendChild( ), prependChild( ), insertChildBefore( ), or insertChildAfter( ). 方法:

// Create an XML instance to work with
var example:XML = <example/>;

// Append a two element node containing a text node child
// with value 2
example.appendChild( <two>2</two> );

// Prepend a one element node containing a text node child
// with value "number 1"
example.prependChild( <one>"number 1"</one> );

// After the one element node, insert a text node with
// value 1.5
example.insertChildAfter( example.one[0], 1.5 );

// Before the two element node, insert a part element node
// containing a text node child with value 1.75
example.insertChildBefore( example.two[0], <part>1.75</part> );

/* Displays:
<example>
 <one>"number 1"</one>

1.5
 <part>1.75</part>
 <two>2</two>
</example>
*/
trace( example );

xml元素属性:
 
// Create an XML instance to work with
var example:XML = <example><someElement/></example>;

// Add some attributes to the someElement element node
example.someElement.@number = 12.1;
example.someElement.@string = "example";
example.someElement.@boolean = true;
example.someElement.@array = ["a", null, 7, undefined, "c"];

/* Displays:
<example>
 <someElement number="12.1" string="example" boolean="true"
 array="a,,7,,c"/>
</example>
*/
trace( example );

当然属性值不能有“-”否则必须用 []

example.someElement.@["bad-variable-name"] = "yes";

还可以这样付值

example.someElement.@["color" + num] = "red";

读xml :

遍历xml :

var menu:XML = <menu>
 <menuitem label="File">
 <menuitem label="New"/>
 </menuitem>
 <menuitem label="Help">
 <menuitem label="About"/>
 </menuitem>
 This is a text node
 </menu>;

for each ( var element:XML in menu.elements( ) ) {
 /* Displays:
 File
 Help
 */
 trace( element.@label );
}

这个方法只能遍历直接childrens类型元素(不包括其他节点,例如text). ,如果全都遍历,可以递归:

var menu:XML = <menu>
 <menuitem label="File">
 <menuitem label="New"/>
 </menuitem>
 <menuitem label="Help">
 <menuitem label="About"/>
 </menuitem>
 This is a text node
 </menu>;

/* Displays:
File
New
Help
About
*/
walk( menu );

// A recursive function that reaches every element in an XML tree
function walk( node:XML ):void {
 // Loop over all of the child elements of the node
 for each ( var element:XML in node.elements( ) ) {
 // Output the label attribute
 trace( element.@label );
 // Recursively walk the child element to reach its children
 walk( element );
 }
}

查找xml元素by name:

var fruit:XML = <fruit><name>Apple</name></fruit>;

// Displays: Apple
trace( fruit.name );
var author:XML = <author><name><firstName>Darron</firstName></name></author>;

// Displays: Darron
trace( author.name.firstName );

双点语法省略.name :

var author:XML = <author><name><firstName>Darron</firstName></name></author>;
// Displays: Darron
trace( author..firstName );

中括号前边不能用双点,例如这就错了:

trace( fruit..[nodeName] ); //error

类似数组的语法:

var items:XML = <items>
 <item>
 <name>Apple</name>
 <color>red</color>
 </item>
 <item>
 <name>Orange</name>
 <color>orange</color>
 </item>
 </items>;
 
// Displays: Apple
trace( items.item[0].name );
// Displays: Orange
trace( items.item[1].name );
// Displays: 2
trace( items.item.length( ) );

读不同类型的值:

var example:XML = <example>
 <bool>true</bool>
 <integer>12</integer>
 <number>.9</number>
 </example>;

// Convert a text node of "true" to boolean true
var bool:Boolean = Boolean( example.bool );

// Convert a text node of "12" to an integer
var integer:int = int( example.integer );

// Convert a text node of ".9" to a number
var number:Number = example.number;

/* Displays:
true
12
.9
*/
trace( bool );
trace( integer );
trace( number );

但是上边的true如果是tRue,或trUe的话,就会出错:

//注意boolean值大小写不同,会出问题所以我们
var bool:Boolean = example.bool.toLowerCase( ) == "true";
//这样处理一下,先转小写,再付值

toString():


var fruit:XML = <fruit>
 <name>Apple</name>
 An apple a day...
 </fruit>;

// Explicity using toString( ) here is required
var value:String = fruit.toString( );

/* Displays:
<fruit>
 <name>Apple</name>
 An apple a day...
</fruit>
*/
trace( value );

遍历文本节点:text()方法


var fruit:XML = <fruit>
 <name>Apple</name>
 An apple a day...
 </fruit>;

for each ( var textNode:XML in fruit.text( ) ) {
 // Displays: An apple a day...
 trace( textNode );
}

读取节点属性:attributes( ) 返回xmllist


var fruit:XML = <fruit name="Apple" color="red" />;

// Use the attributes( ) method and save the results as an XMLList
var attributes:XMLList = fruit.attributes( );

// Displays: Apple
trace( attributes[0] );
// Displays: red
trace( attributes[1] );

节点属性名:


var fruit:XML = <fruit name="Apple" color="red" />;

// Displays: color
trace( fruit.attributes( )[1].name( ) );

再看一遍


var fruit:XML = <fruit name="Apple" color="red" />;

for each ( var attribute:XML in fruit.attributes( ) ) {
 /* Displays:
 name = Apple
 color = red
 */
 trace( attribute.name( ) + " = " + attribute.toString( ) );
}

如果直接知道属性名可以:


var fruit:XML = <fruit name="Apple" color="red" />;

// Displays: red
trace( fruit.@color );
//或
trace( fruit.attribute("color") );

可以用*代替attributes( )


var fruit:XML = <fruit name="Apple" color="red" />;

// Displays: Apple
trace( fruit.@*[0] );

// Displays: red
trace( fruit.@*[1] );

// Displays: 2
trace( fruit.@*.length( ) );

//Because the attributes are always returned as an XMLList, the attributes are indexable, making them easy to access.

双点在@前边表示整个xml:


// Create a fictitious shopping cart
var cart:XML = <cart>
 <item price=".98">crayons</item>
 <item price="3.29">pencils</item>
 <group>
 <item price=".48">blue pen</item>
 <item price=".48">black pen</item>
 </group>
 </cart>;

// Create a total variable to represent represent the cart total
var total:Number = 0;

// Find every price attribute, and add its value to the running total
for each ( var price:XML in cart..@price ) {
 total += price;
}

// Displays: 5.23
trace( total );

删除: 节点,文本节点,属性


var example:XML = <example>
 <fruit color="Red">Apple</fruit>
 <vegetable color="Green">Broccoli</vegetable>
 <dairy color="White">Milk</dairy>
 </example>;
 
// Remove the color attribute from the fruit element
delete example.fruit.@color;

// Remove the dairy element entirely
delete example.dairy;

// Remove the text node from the vegetable element node
delete example.vegetable.text( )[0];

/* Displays:
<example>
 <fruit>Apple</fruit>
 <vegetable color="Green"/>
</example>
*/
trace( example );

成批删除:你需要得到一个xmllist并且遍历它
 

//像 text( ) , elements( ) on an XML object, 或者 一些情况下的E4X 语法都可以得到xmllist

var example:XML = <example>
 <fruit color="red" name="Apple" />
 </example>;

// Get an XMLList of the attributes for fruit
var attributes:XMLList = example.fruit.@*;

// Loop over the items backwards to delete every attribute.
// By removing items from the end of the array we avoid problems
// with the array indices changing while trying to loop over them.
for ( var i:int = attributes.length( ) - 1; i >= 0; i-- ) {
 delete attributes[i];
}

/* Displays:
<example>
 <fruit/>
</example>
*/
trace( example );

loading xml


package {
 import flash.display.*;
 import flash.events.*;
 import flash.net.*;
 import flash.util.*;

 public class LoadXMLExample extends Sprite {
 
 public function LoadXMLExample( ) {
 var loader:URLLoader = new URLLoader( );
 loader.dataFormat = DataFormat.TEXT;
 loader.addEventListener( Event.COMPLETE, handleComplete );
 loader.load( new URLRequest( "example.xml" ) );
 }
 
 private function handleComplete( event:Event ):void {
 try {
 // Convert the downlaoded text into an XML instance
 var example:XML = new XML( event.target.data );
 // At this point, example is ready to be used with E4X
 trace( example );
 
 } catch ( e:TypeError ) {
 // If we get here, that means the downloaded text could
 // not be converted into an XML instance, probably because
 // it is not formatted correctly.
 trace( "Could not parse text into XML" );
 trace( e.message );
 }
 }
 }
}

sending xml


package {
 import flash.display.*;
 import flash.text.*;
 import flash.filters.*;
 import flash.events.*;
 import flash.net.*;

 public class XMLSendLoadExample extends Sprite {
 
 private var _message:TextField;
 private var _username:TextField;
 private var _save:SimpleButton;
 
 public function XMLSendLoadExample( ) {
 initializeDispaly( );
 }
 
 private function initializeDispaly( ):void {
 _message = new TextField( );
 _message.autoSize = TextFieldAutoSize.LEFT;
 _message.x = 10;
 _message.y = 10;
 _message.text = "Enter a user name";
 
 _username = new TextField( );
 _username.width = 100;
 _username.height = 18;
 _username.x = 10;
 _username.y = 30;
 _username.type = TextFieldType.INPUT;
 _username.border = true;
 _username.background = true;
 
 _save = new SimpleButton( );
 _save.upState = createSaveButtonState( 0xFFCC33 );
 _save.overState = createSaveButtonState( 0xFFFFFF );
 _save.downState = createSaveButtonState( 0xCCCCCC );
 _save.hitTestState = save.upState;
 _save.x = 10;
 _save.y = 50;
 // When the save button is clicked, call the handleSave method
 _save.addEventListener( MouseEvent.CLICK, handleSave );
 
 addChild( _message );
 addChild( _username );
 addChild( _save );
 }
 
 // Creates a button state with a specific background color
 private function createSaveButtonState( color:uint ):Sprite {
 var state:Sprite = new Sprite( );
 
 var label:TextField = new TextField( );
 label.text = "Save";
 label.x = 2;
 label.height = 18;
 label.width = 30;
 var background:Shape = new Shape( );
 background.graphics.beginFill( color );
 background.graphics.lineStyle( 1, 0x000000 );
 background.graphics.drawRoundRect( 0, 0, 32, 18, 9 );
 background.filters = [ new DropShadowFilter( 1 ) ];
 
 state.addChild( background );
 state.addChild( label );
 return state;
 }
 
 private function handleSave( event:MouseEvent ):void {
 // Generate a random score to save with the username
 var score:int = Math.floor( Math.random( ) * 10 );
 
 // Create a new XML instance containing the data to be saved
 var dataToSave:XML = <gamescore>
 <username>{username.text}</username>
 <score>{score}</score>
 </gamescore>;
 
 // Point the request to the script that will handle the XML
 var request:URLRequest = new URLRequest( "/gamescores.cfm" );
 // Set the data property to the dataToSave XML instance to send the XML
 // data to the server
 request.data = dataToSave;
 // Set the contentType to signal XML data being sent
 request.contentType = "text/xml";
// Use the post method to send the data
 request.method = URLRequestMethod.POST;
 
 // Create a URLLoader to handle sending and loading of the XML data
 var loader:URLLoader = new URLLoader( );
 // When the server response is finished downloading, invoke handleResponse
 loader.addEventListener( Event.COMPLETE, handleResponse );
 // Finally, send off the XML data to the URL
 loader.load( request );
 }
 
 private function handleResponse( event:Event ):void {
 try {
 // Attempt to convert the server's response into XML
 var success:XML = new XML( event.target.data );
 
 // Inspect the value of the success element node
 if ( success.toString( ) == "1" ) {
 _message.text = "Saved successfully.";
 } else {
 _message.text = "Error encountered while saving.";
 }
 
 } catch ( e:TypeError ) {
 // Display an error message since the server response was not understood
 _message.text = "Could not parse XML response from server.";
 }
 }
 }
}

分享到:
评论

相关推荐

    IE E4X - Intuitive XML access-开源

    3. **XML列表和集合**:E4X中的XML列表类似于数组,可以方便地遍历和操作XML节点集合。 4. **XML构造**:可以通过JavaScript表达式动态构造XML文档,如`new XML("&lt;element&gt;text&lt;/element&gt;")`。 5. **查询和筛选**...

    x-SCAN -V3.3-CN.

    对远程操作系统识别功能进行了加强,并去掉了一些可由脚本完成的插件。 感谢isno和Enfis提供优秀插件,感谢悟休、quack帮忙精选nasl脚本列表,也感谢其他提供优秀思路和协助测试的朋友。 X-Scan v2.3 -- 发布日期...

    强大的扫描工具x-scan

    X-Scan v1.0(beta) -- 发布日期:07/12/2001,新增对远程操作系统类型及版本识别功能;新增对 远程主机地理位置查询功能;在“-iis”选项中,新增对IIS “.ida/.idq”漏洞的扫描,同时更新漏洞 描述;在“-port”...

    Foundation+XML+and+E4X+for+Flash+and+Flex And sourcecode

    通过阅读《Foundation XML and E4X for Flash and Flex》并研究提供的源代码,开发者不仅可以深化对XML和E4X的理解,还能获得在实际项目中运用这些技术的实践经验,从而提升开发Flash和Flex应用的专业技能。...

    AJAX及使用E4X编写Web服务脚本系列

    E4X(ECMAScript for XML)是JavaScript的一个扩展,旨在简化XML处理,使JavaScript可以更加方便地创建、操作和解析XML文档。E4X将XML直接集成到JavaScript语法中,使得XML数据可以直接作为JavaScript对象进行操作,...

    javascript 操作xml

    4. **E4X(ECMAScript for XML)**: - E4X是ECMAScript的一个扩展,允许在JavaScript代码中直接处理XML。 - `var xml = &lt;root&gt;&lt;item id="1"&gt;Data&lt;/item&gt;&lt;/root&gt;;`:在JavaScript中创建XML结构。 - `xml.item.@id...

    flex 操作XML

    - Flex支持E4X(ECMAScript for XML),它允许直接在JavaScript语法中处理XML。 - 例如,获取XML中的某个节点值: ```actionscript var nodeValue:String = yourXMLNode.@attributeName; ``` - 遍历XML节点: ...

    js-xml.rar_javascript_javascript xml_js xml_js解析xml_xml js

    在一些旧的浏览器环境中,如Firefox,支持E4X,这是一种将XML集成到JavaScript语法中的尝试。它允许直接在JavaScript代码中嵌入XML,但现代浏览器已经不再支持此特性。 7. jQuery和XML: jQuery库简化了...

    flash通过xml调用外部文件示例

    在Flash中,我们可以使用XMLLoader类或者E4X(ECMAScript for XML)语法来加载XML文件。一旦XML数据加载完成,我们可以通过解析XML结构来实现自动播放等功能。例如,如果XML文件包含一个音视频资源列表,每个元素都...

    web的xml技术

    - **E4X**:ECMAScript for XML,一种扩展的JavaScript版本。 - **简化XML处理**:内置对XML的支持。 #### DTD教程 - **DTD简介**:Document Type Definition,定义XML文档结构的规范。 - **DTD元素**:定义文档中...

    AS3中新的XML处理方法.pdf

    E4X提供了许多直观的方法和操作符来操作XML数据: - **访问节点**:使用数组索引或`child`属性访问子节点。 - **访问属性**:使用`@`操作符访问属性。 - **遍历节点**:使用`for`循环或`XMLList`类型进行遍历。 ...

    flash 从xml中获取数据

    4. E4X(ECMAScript for XML)路径表达式进行XML操作 5. 遍历和访问XML节点及其属性 对于初学者,深入理解和实践这些概念将对掌握Flash与XML的交互大有裨益。同时,不断探索和优化代码,以提高效率和可读性,是成为...

    解析xml,ajax

    - E4X(ECMAScript for XML):E4X是JavaScript的一种扩展,允许直接在JavaScript中处理XML。例如,`var doc = new XML(xmlString)`可以创建一个XML对象。但需要注意,E4X不是所有浏览器都支持,主要在Firefox中...

    flash+XML基础交互实例

    在IT行业中,Flash和XML是两个非常重要的...了解这些基础知识后,开发者可以进一步探索更复杂的Flash与XML集成,如使用E4X(ECMAScript for XML)语法,或者结合服务器端技术如PHP、ASP.NET等进行更高效的数据交换。

    JS 调用XML文件内容

    5. **E4X(ECMAScript for XML)**:在某些JavaScript环境中,如Flash或旧版的Firefox,支持E4X,它允许直接在JavaScript中嵌入XML,并提供类似于处理JSON的语法来操作XML。然而,E4X在现代浏览器中已不再被支持。 ...

    CppE4X:一个cpp版本的XML解析器,类E4X语法

    E4X是JavaScript的一个扩展,使得在JavaScript中操作XML变得更为简洁和直观。CppE4X的目标就是将这种便利性引入到C++编程环境中。 **XML解析的基本概念** XML(eXtensible Markup Language)是一种用于标记数据的...

    E4A MQTT 类库 安卓

    "窗口树.xml"、"代码树.xml"、"线程树.xml"、"服务树.xml"、"接口树.xml"分别定义了应用程序的界面结构、代码组织、线程管理、服务和接口等。"res"目录包含了应用程序的资源文件,如图片、字符串等。"assets"通常...

    ActionScript 3.0 开发人员指南中文官网上下的

    - **用于处理XML的E4X方法**:介绍了一些常用的E4X方法,如 `XML` 对象的 `toString()`、`children()` 等。 - **XML对象**:`XML` 类提供了丰富的接口来操作XML文档。 - **XMLList对象**:`XMLList` 类用来处理XML...

    Flex基础培训-6-拖放与过滤

    相比之前的版本,E4X极大地简化了对XML数据的操作过程,减少了代码量并提高了效率。 #### E4X操作示例 以下是一个简单的XML文档示例: ```xml &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;name&gt;ZhangSan &lt;age&gt;...

    LoadXML.rar_flex

    加载XML后,可以使用E4X语法或传统的DOM方法来访问和操作XML节点。例如,获取XML文件中的特定元素值: ```actionscript var value:String = xml.child("element_name").toString(); ``` 5. **程序初始化**: ...

Global site tag (gtag.js) - Google Analytics