E4X-Examples of XML operations

Source: Internet
Author: User
Write XML:VaR example: xml = <ABC> <A> eh </a> <B> bee </B> <C> See </C> </ABC>;

Write with variables:// 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>;

String:// 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 );

Add Element// Create an XML instance to add elements
VaR example: xml = <example/>;

// Create a New XML node named newelement and add it to
// Example instance
Example. newelement = <newelement/>;

/* Displays:
<Example>
<Newelement/>
</Example>
*/
Trace (example );

TIPS:// Create an XML instance to work
VaR example: xml = <example/>;

VaR ID: Int = 10;

// Create a string to induplicate ate the value of ID in the node name
Example ["user" + id] = "";

/* Displays:
<Example>
<User10/>
</Example>
*/
Trace (example );

"-" Will cause a compiler error. Use the array operator to avoid thisExample. Some-element = ""; // generates a compiler Error

Example ["Some-element"] = "";

Insertchildbefore and insertchildafter// Create an XML instance to work
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 );

Add the text node to xmlobject:// Create an XML instance to work
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 (). Method:// Create an XML instance to work
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
// 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 Element attributes:// Create an XML instance to work
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>
& Lt; someelement number = "12.1" string = "example" Boolean = "true"
Array = "A, 7, C"/>
</Example>
*/
Trace (example );

Of course, the attribute value cannot contain "-". Otherwise, you must use [].Example. someelement. @ ["Bad-variable-name"] = "yes ";

You can also pay the value in this way.Example. someelement. @ ["color" + num] = "red ";

Read XML:

Traverse 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 );
}

This method can only traverse elements of the childrens type directly (excluding other nodes, such as text). If all elements are traversed, recursion can be performed: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 );
}
}

Search for the XML element 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 );

Double point syntax omitted. Name:VaR Author: xml = <author> <Name> <firstname> Darron </firstname> </Name> </author>;
// Displays: Darron
Trace (author .. firstname );

The front and side of the brackets cannot use double points. For example, this is an error:Trace (fruit... [nodename]); // Error

Syntax similar to array: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 ());

Read different types of values: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 );

However, if the preceding value is true or true, an error occurs:// Note that the values of Boolean are case-insensitive.
VaR bool: Boolean = example. bool. tolowercase () = "true ";
// In this way, convert it to lowercase and then pay the value.

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 );

Traverse text nodes: Text () methodVaR 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 );
}

Read node attribute: attributes () returns xmllistVaR 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]);

Node attribute name:VaR fruit: xml = <fruit name = "apple" color = "red"/>;

// Displays: Color
Trace (fruit. attributes () [1]. Name ());

Try againVaR 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 ());
}

If you know the property name, you can:VaR fruit: xml = <fruit name = "apple" color = "red"/>;

// Displays: red
Trace (fruit. @ color );
// Or
Trace (fruit. Attribute ("color "));

You can use * to replace 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.

Vertices represent the entire XML in front:// 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 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 );

Delete: node, text node, attributeVaR 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 );

Batch Delete: You need to get an xmllist and traverse it.// Xmllist can be obtained for text (), elements () on an XML object, or E4X syntax in some cases.

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 XMLPackage {
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.tar get. 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 cocould
// Not be converted into an XML instance, probably because
// It is not formatted correctly.
Trace ("cocould not parse text into XML ");
Trace (E. Message );
}
}
}
}

Sending XMLPackage {
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 (0 xffffff );
_ Save. downstate = createsavebuttonstate (0 xcccccc );
_ 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.tar get. 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 = "cocould not parse XML response from server .";
}
}
}
}

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.