FLEX中关于XML的操作

XML具有健壮的结构化、简单易于理解、天生的跨平台跨应用数据传输优势,且FLEX和AS支持E4X标准的XML语法,使得在其中对XML操作极为方便简单。能灵活的使用XML往往能使我们的工作如虎添翼,下面总结下FLEX中关于XML的操作。

 

1、创建XML对象:

   1.1、直接写在等号右边,赋值给XML变量:

   var xml:XML =  

   用变量填充XML:

   var name:String = "mary"; var sex:String = "female"; var xml:XML =

   1.2、将XML结构的字符串作为参数传给XML构造函数返回XML对象:

   var xml:XML = new XML(''); 

   1.3、从外部源载入XML对象:

   //载入北京海淀未来7天天气预报rss var loader:URLLoader = new URLLoader(); loader.dataFormat = "e4x"; loader.addEventListener(Event.COMPLETE, onComplete); loader.load(new URLRequest("http://weather.raychou.com/?/detail/54399/rss")); private function onComplete(event:Event):void { var weather:XML = new XML(event.target.data); }


2、读取XML数据:

   //构造示例XML对象 var employees:XML = 555-219-2270 [email protected] true 555-219-2012 [email protected] [email protected]

   //遍历XML的子节点 for each (var employee:XML in employees.elements()) { trace(employee.toXMLString()) } var employee1:XML = employees.elements()[0]; //employees的第一个子元素 var parent:XML = employee1.parent(); //读取xml的父节点 //使用"@"操作读取xml的属性 trace(employee1.@name); //Christina Coenraets //使用"attribute(attr_name)"函数读取xml的属性 trace(employee1.attribute("active")); //true //使用"[name]"操作读取所有名为"email"的节点,返回XMLList对象 var emails:XMLList = employees.employee["email"]; trace(emails.length()) //2 //使用"."操作读取所有名为"email"的节点,返回XMLList对象 var theEmails:XMLList = employees.employee.email; trace(theEmails.length()) //2 //使用".."操作读取所有深度名为email的节点,范围XMLList对象 var allEamils:XMLList = employees..email; //使用"child(name)"函数读取所有名为"phone"的节点,返回XMLList对象 var phones:XMLList = employees.employee.child("phone"); trace(allEamils.length()) //3 

 

3、增加XML子节点、属性:

var employee:XML = ; //增加属性 employee.@id = "1314"; //用字符串赋值,增加子节点 employee.email = "[email protected]"; //使用"appendChild(object)"函数,在末尾插入子节点 employee.appendChild(male); //使用"prependChild(object)"函数,在首部插入子节点 employee.prependChild(Joanne Wall); //用XML对象赋值,增加子节点 employee.nationality = USA; //使用"insertChildAfter(object1, object2)"函数,在object1后插入子节点 employee.insertChildAfter(employee.child("name"), false); //使用"insertChildBefore(object1, object2)"函数,在object1前插入子节点 employee.insertChildBefore(employee.child("active"), 555-219-2012); trace(employee.toXMLString()) /** 输出结果: Joanne Wall 555-219-2012 false [email protected] male USA */

 

4、删除XML子节点、属性:

   var employee:XML = 555-219-2012 [email protected] ; delete employee.@id; delete employee.phone; trace(employee.toXMLString()); /** 输出结果: [email protected] */ 

 

5、搜索查找指定节点:

   var employees:XML = Christina Coenraets 555-219-2270 [email protected] Joanne Wall 555-219-2012 [email protected] ; //属性id为13的子节点 var Christina:XML = employees.employee.(@id == 13)[0]; //name元素为"Joanne Wall"的子节点 var Joanne:XML = employees.employee.(name == "Joanne Wall")[0]; var other:XML = employees..*.(hasOwnProperty( "@id" ) && @id == "2012")[0]; // 

你可能感兴趣的:(FLEX)