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.";
 }
 }
 }
}

阅读更多
文章标签: XML Apple Flash C C++
个人分类: actionscript
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭