AS3 CookBook学习整理(十六)

本文详细介绍了如何使用ActionScript进行XML的基本操作,包括读取属性、删除元素、加载XML、发送XML数据、搜索XML、使用HTML及特殊字符等。此外还讲解了在Flex中调用WebServices的方法,以及ActionScript与JavaScript之间的互调技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 读取XML元素的属性

假设有下面的xml:

xml:XML =  <menu>
   <item title= author=>栏目A</item>
   <item title= author=>栏目B</item>
   <distinctItem><subItem>特别栏目</subItem></distinctItem>
   <item title= author=>栏目C</item>
  </menu>;

得到某个节点的某个属性

xml.item[1].@author

得到某个节点的所有属性,调用name( ) 方法可显示出属性名

attrList:XMLList = xml.item[1].attributes();
(node:XML    attrList)
{
 (node.name() +  + node);
}

调用attribute("attrName")来得到所有名称为"attrName"的属性

attrList:XMLList = xml.item.attribute();
(node:XML    attrList)
{
 (node);
}

可以使用操作符 * 和 @ 来得到所有属性

list:XMLList = xml..@*;   
(attr:XML    list)
{
 (attr.name() +  + attr);
}

2. 删除XML元素,文本节点和属性

使用delete关键字

 {
 flash.display.Sprite;
  Sample0709Sprite
 {
   Sample0709()
  {
   xml:XML =  <menu>
      <item title= author=>栏目A</item>
      <item title= author=>栏目B</item>
      <distinctItem><subItem>特别栏目</subItem></distinctItem>
      <item title= author=>栏目C</item>
     </menu>;   
    
   delete xml.item[1].text()[0];
    
   delete xml.item[0];
 
delete xml.distinctItem.subItem;
delete xml.item.@*; (xml); } } }

3. 载入XML

使用URLLoader.load()方法并且设置dataFormat属性为DataFormat.TEXT读取数据,通过complete事件转换载入的数据为XML实例

PS:为避免非XML正常格式带来的转换错误,应该加入异常处理(捕获TypeError)

 {
 flash.display.Sprite;
 flash.events.Event;
 flash.net.URLLoader;
 flash.net.URLLoaderDataFormat;
 flash.net.URLRequest;
 flash.system.System;
  Sample0710Sprite
 {
   Sample0710()
  {
   flash.system.System.useCodePage = ;
   loader:URLLoader = URLLoader(URLRequest());
   loader.dataFormat = URLLoaderDataFormat.TEXT;
   loader.addEventListener(Event.COMPLETE,onComplete);
  }
  
   onComplete(event:Event):
  {
   
   {
    xml:XML = XML(event.target.data);
    delete xml..channel[0];
    (xml);
   }
   (e:TypeError)
   {
    ();
    (e.message);
   }
  }
 }
}

4. 发送XML数据给服务端脚本

调用sendToURL()和navigateToURL()发送数据,注意设置URLRequest的如下属性:

request.data = xml; //一个xml对象

request.contentType = "text/xml";

request.method = URLRequestMethod.POST;

服务器端代码(.net)

void Page_Load(object sender, EventArgs e)
{
    XmlDocument xml = XmlDocument();
    xml.Load(Request.InputStream);
    
    XmlNodeList nodeList = xml.SelectSingleNode().ChildNodes;
    for (int i = 0; i < nodeList.Count; i++)
    {
        Response.Write(nodeList.Item(i).Attributes[0].Value +  + nodeList.Item(i).InnerXml + );
    }
}

flex代码:

 {
 flash.display.Sprite;
 flash.events.MouseEvent;
 flash.net.URLRequest;
 flash.net.URLRequestMethod;
 flash.net.navigateToURL
  Sample0710Sprite
 {
  request:URLRequest;
  
   Sample0710()
  {
   xml:XML =  <musicBox>
      <song author=>花沙</song>
      <song author=>于心有愧</song>
      <song author=>日光恋人</song>
     </musicBox>;
       
   request = URLRequest();
   request.data = xml;
   request.contentType = ;
   request.method = URLRequestMethod.POST;
   
   stage.addEventListener(MouseEvent.CLICK,onClick);
  }
  
   onClick(event:MouseEvent):
  {
   navigateToURL(request);
  }
 }
}

5. 搜索XML

假如有如下的XML:

xml:XML =  <foodGroup>
   <fruits>
    <fruit color=>苹果</fruit>
    <fruit color=>香蕉</fruit>
    <fruit color=>西瓜</fruit>
    <fruit color=>鸭梨99</fruit>
   </fruits>
   <vegetables>
    <vegetable color=>西红柿</vegetable>
    <vegetable color=>土豆</vegetable>
    <vegetable color=>茄子</vegetable>
   </vegetables>
  </foodGroup>;

直接通过点操作符定位

singleNode:XML = xml.fruits.fruit[0]; 
nodeList:XMLList = xml.fruits.fruit; 
   
(node:XML    nodeList)
{
 (node);
}

通过双点操作符得到未知路径下的节点

nodeList:XMLList = xml..vegetable;
(node:XML    nodeList)
{
 (node);
}

通过 * 操作符得到任意节点

nodeList:XMLList = xml.*.fruit;
(node:XML    nodeList)
{
 (node);
}

@ 符号用来访问属性

nodeList:XMLList = xml.fruits.fruit.@color;
(node:XML    nodeList)
{
 (node);
}

调用hasOwnProperty("attributeName")检查是否有某属性

nodeList:XMLList = xml..fruit.(!hasOwnProperty());
(node:XML    nodeList)
{
 (node);
}

检查节点的属性值

nodeList:XMLList = xml..fruit.(@color==);
(node:XML    nodeList)
{
 (node);
}

检查节点值,并应用正则表达式

nodeList:XMLList = xml.fruits.fruit;
(node:XML    nodeList)
{
 (node==)
 {
  (node.@color);
 }
 (/\d/.test(node))
 {
  (node);
 }
}

6. 在XML中使用HTML和特殊字符

使用CDATA标签,以 <![CDATA[ 开始,以 ]]> 结束

 {
 flash.display.Sprite;
 flash.net.URLRequest;
  Sample0710Sprite
 {
  request:URLRequest;
  
   Sample0710()
  {
   xml:XML =  <menu>
      <item><![CDATA[a>b]]></item>
      <item><![CDATA[<a href=>链接</a>]]></item>
     </menu>;
   
   (node:XML    xml.elements())
   {
    (node);
   }
  }
 }
}

7. 在Flex里调用WebServices

Flash播放器没有内建web services支持,也不理解SOAP;不过Flash播放器能在HTTP上通讯,能解析XML数据,实际上SOAP web services也是在HTTP上通讯且SOAP协议也是以XML为基础的协议,因此用ActionScript完全可以调用web services方法,Flex framework 提供了解决方案

WebServices代码:(.net)

[WebMethod]
string HelloWorld()
{
     ;
}
[WebMethod]
string GetUser(string name, int age)
{
     name +  + age + ;
}

Flex代码:

<?xml version= encoding=?>
<mx:Application xmlns:mx= layout=>
 <mx:WebService id= wsdl=>
  <mx:operation name= result= fault=>
  </mx:operation>
  <mx:operation name= result= fault=>
   <mx:request>
    <name>臣本布衣</name>
    <age>26</age>
   </mx:request>
  </mx:operation>
 </mx:WebService>
 
 <mx:Text id= x= y=></mx:Text>
 
 <mx:Button label= click= x= y=></mx:Button>
 <mx:Button label= click= x= y=></mx:Button>
 
 <mx:Script>
  <![CDATA[
   mx.rpc.events.FaultEvent;
   mx.rpc.events.ResultEvent;
    onResult(event:ResultEvent):
   {
    .txtValue.text = event.result.toString();
   }
    onFault(event:FaultEvent):
   {
    .txtValue.text = event.fault.toString();
   }
  ]]>
 </mx:Script>
</mx:Application>

8. AS调用Javascript函数

如果是比较简单的调用(例如alert('abc');),可以直接利用navigateToURL,这也是兼容所有浏览器的做法:

navigateToURL(new URLRequest("javascript:alert('老胡');"), "_self");

navigateToURL(new URLRequest("javascript:myFunc('老胡',27);"), "_self");

一般情况下应该使用ExternalInterface.call(funcName, parameters);

Javascript代码:

<script type=>
     saySomething(name, age) 
    {
        alert(name +  + age + );
    }
     getSomething() 
    {
         ;
    }
</script>

AS3代码:

 {
 flash.display.Sprite;
 flash.events.MouseEvent;
 flash.external.ExternalInterface;
 flash.net.URLRequest;
 flash.net.navigateToURL;
 flash.text.TextField;
  Sample0721Sprite
 {
  textBox:TextField;
  
   Sample0721()
  {
   button:Sprite = Sprite();
   button.graphics.beginFill(0xFF0000);
   button.graphics.drawRect(100,100,100,50);
   button.graphics.endFill();
   button.addEventListener(MouseEvent.CLICK,button_Click)
   .addChild(button);
   
   textBox = TextField();
   textBox.text = ;
   textBox.x = textBox.y = 200;
   textBox.addEventListener(MouseEvent.CLICK,textBox_Click);
   .addChild(textBox);
  }
  
   button_Click(event:MouseEvent):
  {
   ExternalInterface.call(,,26); 
  }
  
   textBox_Click(event:MouseEvent):
  {
   textBox.text = ExternalInterface.call();
  }
 }
}

PS:要注意在HTML代码里嵌入swf文件的方式,之前仅仅用了Embed嵌入,导致了IE无法获得Javascript函数的返回值

9. Javascript调用AS函数

使用ExternalInterface.addCallback(jsFuncName, asFuncName)

在客户端需要得到Flash播放器的对象引用,浏览器中的Flash播放器有两种类型:ActiveX和plug-in版本,ActiveX版本运行在Internet Explorer上,而plug-in版本运行在其它浏览器上

ActiveX版本播放器由HTML页中的

一般情况下,我们并不知道用户使用什么版本的Flash播放器,有个方法是通过JavaScript的navigator.appName来检测用户浏览器的类型:

如果navigator.appName 包含Microsoft关键字,那么用户使用的就是Internet Explorer,也就是ActiveX 播放器

如果navigator.appName 不包含Microsoft关键字,也就意味着是plug-in 版本播放器

AS代码:

 {
 flash.display.Sprite;
 flash.external.ExternalInterface;
  Sample0721Sprite
 {
   Sample0721()
  {
   ExternalInterface.addCallback(,addRectToStage);
  }
  
   addRectToStage():String
  {
   circle:Sprite = Sprite();
   circle.graphics.beginFill(0xFFFF00);
   circle.graphics.drawCircle(Math.random()*300,Math.random()*300,20);
   circle.graphics.endFill();
   
   .addChild(circle);
   
    ;
  }
 }
}

Javascript代码:

<script type=>
 callAS() 
{
 flashPlayer;
 if (navigator.appName.indexOf() != -1) 
 {
  flashPlayer = document.getElementById();
 }
 else 
 {
  flashPlayer = document[];
 }
    alert(flashPlayer.drawCircle());
}
</script>

10. 从HTML传递参数给Flash

使用FlashVars以"key1=value1&key2=value2"的形式传递参数(如果有特殊符号,例如&,需要用URL编码为%26),Flash端通过root.loaderInfo.parameters得到该FlashVars数组的引用

HTML代码:

<object classid=>
 <param name= value=>
 <embed type= FlashVars=>
</object>

AS3代码:

 {
 flash.display.Sprite;
 flash.text.TextField;
  Sample0721Sprite
 {
   Sample0721()
  {
   label:TextField = TextField();
   .addChild(label);
   
   obj:Object = root.loaderInfo.parameters;
   label.text = obj.userName;
  }
  
 }
}

 

转载于:https://www.cnblogs.com/CoderWayne/archive/2010/07/15/1778086.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值