通过传递数据引用创建XML对象
前边介绍XML的例子展示了使用XML文档初始化XML对象的方法。当创建一个XML文档时,你也可以通过引用(来自其他变量的引用)传递数到XML对象中,通过大括号扩起来的变量值引用。
如果你创建的XML结构不是有效的XML,你会看到类型错误的运行时错误。
下边的例子动态的创建了一个XML对象。它基于用户提供的变量来创建属性名,属性值,标签名和标签内容。例子检查了TypeError的情况,通过使用try…catch块环绕XML初始化代码。
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="500" height="400" initialize="createXML();" > <mx:Script> <!--[CDATA[ [Bindable] public var xml:XML private function createXML():void { try { // Create the XML object using the values provided // by the user for the tag name, attribute name, // attribute value and the tag's contents. xml = <{tagName.text} {attributeName.text}={attributeValue.text} > {content.text} </{tagName.text}>; } catch (e:TypeError) { // Type error encountered while trying to create the // XML object. The form must not be valid. Inform // the user. xml = <note>Fill the form to see the tag here.</note>; } } ]]--> </mx:Script> <!-- User interface --> <mx:Panel title="Passing XML data by reference" layout="horizontal" > <mx:Form> <mx:FormItem label="Tag name:"> <mx:TextInput id="tagName" change="createXML();"/> </mx:FormItem> <mx:FormItem label="Attribute name:"> <mx:TextInput id="attributeName" change="createXML();"/> </mx:FormItem> <mx:FormItem label="Attribute value:"> <mx:TextInput id="attributeValue" change="createXML();"/> </mx:FormItem> <mx:FormItem label="Tag content:"> <mx:TextInput id="content" change="createXML();"/> </mx:FormItem> <mx:HRule width="100%"/> <!-- Display the resulting XML --> <mx:TextArea editable="false" width="300" height="50" text="{xml.toXMLString()}" /> </mx:Form> </mx:Panel> </mx:Application>
本文介绍了一种使用ActionScript动态创建XML对象的方法,并演示了如何通过用户输入的数据引用创建合法的XML结构。文中提供了一个示例代码,展示了如何处理类型错误并显示最终生成的XML。
1513

被折叠的 条评论
为什么被折叠?



