A new XML processing method in AS3-e4x

Source: Internet
Author: User
Tags access properties array contains event listener variables tagname tostring xml attribute
Xml

Today we look at the new XML processing method in AS3: e4x, until now, ECMA Scripting language Specification (ECMA-262)--ascriptscript 3.0 's core Foundation, and does not provide any XML data processing classes or methods. The previous version of Acriontscript (starting with ActionScript in Flash 5) has some classes and methods for processing XML data, but they are not based on the ECMAScript standard.

The new ECMA scripting language Specification, draft version 4th, defines a series of new classes and methods for handling XML data. The collection of these classes and methods is named E4x ("ECMAScript for XML"), and ActionScript 3.0 includes the following new E4X classes: XML, XMLList, QName, and namespace.

The methods, attributes, and operations of the E4X class are based on the following objectives:

Simple--e4x as much as possible so that the code to process XML data is easy to write and easy to understand.
The consistency--e4x approach is coordinated in other parts of ActionScript.
Friendly-practical and very well understood operator handles XML data, such as dot Number (.).
Note: To avoid conflicts with new XML classes in E4X, the XML class in ActionScript 2.0 was renamed to XmlDocument in ActionScript 3.0, for forward compatibility, in ActionScript The remnants of Class--xml, XMLNode, Xmlparser, and xmltag--in 3.0 are included in the Flash.xml package. The new E4X classes are core classes--they don't need to import any packages.

Initializing XML objects

An XML object can represent an XML element, attribute, comment, processing instruction, or text element. In ActionScript 3.0, we can assign XML data directly to variables:

var myxml:xml =
<order>
<item id= ' 1 ' >
<menuName>burger</menuName>
<price>3.95</price>
</item>
<item id= ' 2 ' >
<menuName>fries</menuName>
<price>1.45</price>
</item>

</order> You can also use the new constructor to create an XML object instance from the XML data literal:

var myxml:xml = new XML ("<order><item id= ' 1 ' ><menuname>burger</menuname><price>3.95 </price></item></order> ")

If the XML data is not well-formed (such as fewer end tags), a run-time error occurs.
Note that you can also pass a variable instance into the XML data:

var tagname:string = "Item";
var attributename:string = "id";
var attributevalue:string = 5;
var content:string = "Chicken";
var x:xml = <{tagname} {attributename}={attributevalue}>{content}</{tagname}>;
Trace (x.toxmlstring ())
Output: <item id= "5" >Chicken</item>

In general, our application is to import XML data from an external source, such as a Web service or RSS feed, and here is an example of importing XML data from a remote URL:

var myxml:xml = new XML ();
var xml_url:string = "Http://www.example.com/Sample3.xml";
Create URLRequest.
var myxmlurl:urlrequest = new URLRequest (Xml_url);
Import data using Urlloader.
var myloader:urlloader = new Urlloader (Myxmlurl);
Add an event listener to process the XML data after the XML data import completes.
Myloader.addeventlistener ("complete", xmlloaded);
When the import is complete, create the XML object using the imported data
function xmlloaded (evtobj:event) {
var myxml:xml = XML (Myloader.data);
Trace ("Data loaded.");
}

To demonstrate the clarity of the code, most of the examples in this article are the 1th way to create XML objects directly using text.
E4x contains some intuitive method XML data operators (such as. and @: For accessing properties):

Get the Menuname value for item 1th
Trace (Myxml.item[0].menuname); Output:burger
Get the id attribute value for item 1th
Trace (myxml.item[0]. @id);//output:1
Gets the menuname value of the item with the id attribute of 2
Trace (Myxml.item. ( @id ==2). MenuName); Output:fries
Gets the price value of the item Menuname is burger
Trace (Myxml.item. ( menuname== "Burger"). Price); output:3.95

You can also add a new child node to the XML using the AppendChild () method:

var newitem:xml =
<item id= "3" >
<menuname>medium cola</menuname>
<price>1.25</price>
</item>
Myxml.appendchild (NewItem);

Of course, you can also use the @ and. Operators to update data:

Myxml.item[0].menuname= "Regular Burger";
Myxml.item[1].menuname= "Small fries";
Myxml.item[2].menuname= "Medium Cola";
Myxml.item. (menuname== "Regular burger"). @quantity = "2";
Myxml.item. (menuname== "Small fries"). @quantity = "2";
Myxml.item. (menuname== "Medium Cola"). @quantity = "2";

accessing XML data
You can use. (point number) and. Operator accesses the child nodes of an XML object and accesses the properties of a node using the @ operator. Consider the following XML objects:

var x:xml =
<book isbn= "0942407296" >
<title>baking extravagant pastries with kumquats</title>
<author>
<lastName>Contino</lastName>
<firstName>Chuck</firstName>
</author>
<pageCount>238</pageCount>
</book>
<book isbn= "0865436401" >
<title>emu Care and Breeding</title>
<editor>
<lastName>Case</lastName>
<firstName>Justin</firstName>
</editor>
<pageCount>115</pageCount>
</book>
</order>

The object X.book represents a XMLList object that contains all of the child nodes named Book, and the XMLList contains two XML objects (two book nodes).
Object X.. LastName represents a XMLList object that contains all the LastName properties in the lower part of the XML tree, which contains two XML objects (two LastName properties).
The object x.book.editor.lastname represents a XMLList object for all LastName nodes that contain all of the child nodes with all x objects named book, and that xmllist contains only one XML object (the value is The LastName property of case).

Accessing parent nodes and child nodes
The parent () method returns the parental node of an XML object.
You can access a specific child node using the sequential index value of the child node list, for example, assuming that an XML object x has two child nodes named book, you can access them as follows:

1th Book node
X.BOOK[0]
2nd book node
X.BOOK[1]

To access the grandson node, we can visit the following direct use of the index value of the son and grandson node:

X.BOOK[0].TITLE[0]

However, if X.BOOK[0] has only one child node called title, you can omit the index:

X.book[0].title

Similarly, if the X object has only one book child node and the book node's child node object has only one title object, then two index values can be omitted:

X.book.title

Note that you can also use the child () method to access specific subnodes directly using the name:

var x.xml =
<order>
<book>
<title>Dictionary</title>
</book>
</order>
var childname:string = "book";
Trace (X.child (childname). title)//Output:dictionary

Access Properties
We use the @ operator to access the XmlNode property:

var myxml:xml =
<order>
<item id= ' 1 ' >
<menuName>burger</menuName>
<price>3.95</price>
</item>
<item id= ' 2 ' >
<menuName>fries</menuName>
<price>1.45</price>
</item>
</order>
Get the id attribute value for item 1th
Trace (myxml.item[0]. @id);//output:1

Filtering XML data using attributes or element values
We can use a specific element name and attribute value to navigate to a particular element to consider the following XML object:

var x:xml =
<employeeList>
<employee id= "347" >
<lastName>Zmed</lastName>
<firstName>Sue</firstName>
<position>data analyst</position>
</employee>
<employee id= "348" >
<lastName>McGee</lastName>
<firstName>Chuck</firstName>
&LT;POSITION&GT;JR. Data analyst</position>
</employee>
</employeeList>


The following are the correct access methods:

Employee object LastName as "McGee", 1th employee node
X.employee. (LastName = = "McGee")//The
FirstName node of the Employee object LastName as "McGee", node of 1th employee node
X.employee. (LastName = = "McGee"). FirstName//The FirstName property of this node
ID attribute lastname to "McGee"
X.employee. (LastName = = "McGee"). @id//The value of the id attribute
List of all Employee objects with an id attribute value of 347
X.employee. (@id = = 347)
LastName child node of an employee object with an id attribute value of 347
X.employee. (@id = = 347). lastName
List of employee objects with all ID attribute values greater than 347
X.employee. (@id >)//An XML list with both employee properties
List of employee objects with all position child node values containing "analyst"
X.employee. (Position.tostring () search ("analyst") >-1)

Use for ... in and for each ... in statement
ActionScript 3.0 includes a new for ... in statement that iterates through the XMLList object and a for every ... in statement. For example, consider the following XML objects, myXML and myXML. Item XMLList Object (XML list containing two item XML object nodes):

var myxml:xml =
<order>
<item id= ' 1 ' quantity= ' 2 ' >
<menuName>burger</menuName>
<price>3.95</price>
</item>
<item id= ' 2 ' quantity= ' 2 ' >
<menuName>fries</menuName>
<price>1.45</price>
</item>
</order>

The for ... in statement allows us to iterate through all the property names of the XMLList, which is actually the index value of the node:

var total:number = 0;
for (Var pname:string in myXML.. Item
{
Total + = number (Myxml.item. @quantity [PName]) * Number (myxml.item.price[pname]);
}

For each ... in statement to traverse all nodes of XMLList:

var total2:number = 0;
For each (Var item:xml in myXML ...). Item
{
Total2 + = number (item@quantity) * Number (Item.price);
}

Using the WITH statement
We can use the WITH statement to indicate that subsequent attributes and node values are based on an XML object, the previous for each ... in sample code, the code using the WITH statement is as follows:

var total:number = 0;
For each (the Var item in myXML ...). Item
{
With (item)
{
{The Attributes and node objects within {are all based on the item XML object and all do not need to use item. To access.
Total + + number (@quantity) * Number (price);
}
}
Trace (total);

modifying XML objects
We can use the PrependChild () method or the AppendChild () method to add a node to the front or end of the list of child nodes of the XML object:

var x1:xml = <p>paragraph 1</p>
var x2:xml = <p>paragraph 2</p>
var x:xml = <body></body>
x = X.appendchild (x1);
x = X.appendchild (x2);
x = X.prependchild (<p>paragraph 0</p>);
x = = <body><p>paragraph 0</p><p>paragraph 1</p><p>paragraph 2</p></ Body>

Use the Insertchildbefore () method or the Insertchildafter () method to add a node to the back of a particular node before it is alive:

var x:xml =
<body>
<p>paragraph 1</p>
<p>paragraph 2</p>
</body>
var newnode:xml = <p>paragraph 1.5</p>
x = X.insertchildafter (x.p[0], NewNode)
x = X.insertchildbefore (x.p[2], <p>paragraph 1.75</p>)

Note that we can also use braces ({and}) to refer to variables when constructing XML objects:

var Ids:array = [121, 122, 123];
var names:array = [["Murphy", "Pat"],["Thibaut", "Jean"], ["Smith", "Vijay"]]
var x:xml = new XML ("<employeeList></employeeList>");
for (var i:int = 0; i < 3; i++) {
var newnode:xml = new XML ();
NewNode =
<employee id={ids[i]}>
<last>{names[i][0]}</last>
<first>{names[i][1]}</first>
</employee>
x = X.appendchild (newnode)
}

We can also assign values to XML object nodes using the = operator:

var x:xml =
<employee>
<lastname>Smith</lastname>
</employee>
X.firstname = "Jean";
X. @id = "239";

The above code sets the XML object x to the following:

<employee id= "239" >
<lastname>Smith</lastname>
<firstname>Jean</firstname>
</employee>

We can also use the + and + + operators to link xmllist:

var x1:xml = <a>test1</a>
var x2:xml = <b>test2</b>
var xlist:xmllist = x1 + x2;
Xlist + <c>test3</c>

deleting XML objects
The delete and Deletebyindex methods are defined in the E4X specification to remove specific XML nodes, but in the current version of the ActionScript 3.0 implementation, these two methods are not implemented, all of which we cannot use directly, But we can delete a particular node by traversing the XML tree, removing a specific node, and lastname the new XML object, and we will delete the employee's child node:

Private Function Deletebyindex (xmlnode:xml,index:number): xml{
var newstr:string= ';
newstr+= ' < ' +xmlnode.localname ();
For each (Var att:xml in Xmlnode.attributes ()) {
newstr+= ' +att.localname () + ' = ' +att.tostring () + ' ";
}
newstr+= ' > ';
var i:number=0;
For each (Var node:xml in Xmlnode.children ()) {
if (I!=index)
Newstr+=node.toxmlstring ();
i++;
}
newstr+= ' </' +xmlnode.localname () + '/> ';
return new XML (NEWSTR);
}
var myxml:xml=
<employee id= "239" >
<lastname>Smith</lastname>
<firstname>Jean</firstname>
<address>
<city>shangrao</city>
<load>daihu</load>
<no>5</no>
</address>
</employee>
Myxml=deletebyindex (myxml,0);

The above Deletebyindex function has two parameters, the 1th parameter is the parent node of the deleted node, and the 2nd parameter is the index value of the deleted node in the parent node's child node list. Iterate through the parent node's indexed properties, then iterate through all of its child nodes, skip the nodes we want to delete, and then combine them into a new XML object to return.
If the XML object is very complex, the amount of data must be greater, the implementation of the above deletion node is very low efficiency, all the correct choice or use the E4X definition of the deletion method, but this feature will wait until the next beta version of ActionScript 3.0 to achieve.

XML type Conversions
We can convert XML objects and XMLList objects into strings, and we can also convert strings to XML objects and XMLList objects. By the way, keep in mind that all XML attribute values, names, and literal values are strings.

Convert XML and XMLList objects to strings
Both the XML object and the XMLList object have two member methods: ToString () and the Toxmlstring () method. The Toxmlstring () method returns a string containing all tags, attributes, namespace declarations, and XML object content, as the effect of a complex XML object (including child elements), the ToString () method, and the Toxmlstring () method, However, with a simple XML object (containing only one text element), the ToString () method returns only the textual content of the element:

var myxml:xml =
<order>
<item id= ' 1 ' quantity= ' 2 ' >
<menuName>burger</menuName>
<price>3.95</price>
</item>
<order>
Trace (myXML.item0.menuName.toXMLString ())
Output: <menuName>burger</menuName>
Trace (myXML.item0.menuName.toString ())
Output:burger

Converts a text string to an XML object
We can create an XML object from a string using the new construct method

var x:xml = new XML (' <a>test<b> ');

But if we try to convert a non-XML or structurally incomplete string to an XML object, a run-time error is reported:

var x:xml = new XML (' <a>test '); Throws an error

Reading RSS fead data from the Internet
The following code reads the RSS fead data for this site:

<?xml version= "1.0" encoding= "Utf-8"?>
<mx:application xmlns:mx= "Http://www.macromedia.com/2005/mxml" xmlns= "*" creationcomplete= "Doinit ()" >
<mx:Script>
<! [cdata[
Private Function Doinit (): void{
Getrssdata ("http://blog.eshangrao.com/rss.php", Ta_view);
}
Public Function Getrssdata (url:string, Outtxt:textarea): Void
{
private var myxmlurl:urlrequest = new URLRequest (URL);
private var myloader:urlloader = new Urlloader (Myxmlurl);
Myloader.addeventlistener ("complete", xmlloaded);
}
Private Function xmlloaded (event:event): void{
ta_view.text= ' Load OK ';
var myloader:urlloader = Urlloader (event.target);
Xml.ignoreprocessinginstructions=false;
var myxml:xml =new XML (myloader.data);
private var outstr:string = "";
For each (Var item:xml in Myxml.children ()) {
if (item.localname () = = ' item ') {
Outstr + + "<p><b>" + Item.children () 0.toString () + ":</b></p><p>";
Outstr + + Item.children () 6.toString ();
Outstr + = "<br/><a href= '" + Item.children () 1.toString ();
outstr = "' ><font color= ' #008000 ' >More...</font></a></p> ';
}
}
Ta_view.text=myxml.tostring ();
Ta_view.htmltext = outstr;
}
]]>
</mx:Script>
<mx:canvas width= "100%" height= "100%" >
<mx:textarea id= "Ta_view" >
<mx:layoutConstraints>
<mx:edgeanchor bottom= "top=" "left=" right= "ten"/>
</mx:layoutConstraints>
</mx:TextArea>
</mx:Canvas>
</mx:Application>

Run sample (FlashPlayer8.5 required)
Note that we do not use the node name to access the node directly (don't know why, if you use Item.title to access the title node, the return is empty, may be related to the RDF directive in my RSS XML, if a friend knows the solution, please let me know), Instead, it uses the children () method, which returns all child node objects of an XML object



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.