Working with XML in Flex 3 and Java-part1

Exclusive offer: get 50% off this eBook here
Flex 3 with Java

Flex 3 with Java — Save 50%

Develop rich internet applications quickly and easily using Adobe Flex 3, ActionScript 3.0 and integrate with a Java backend using BlazeDS 3.2

$23.99    $12.00
by Satish Kore | June 2009 | Java Open Source

In this two-part article series by Satish Kore, you will learn how to work with XML data using Flex's E4X approach. In the first part of this article series i.e. this article, we will start with the basics and move ahead to understand E4X completely. In the second part of this article series, we will learn about loading external XML documents, and also look at an example illustrating the explained concepts.

In today's world, many server-side applications make use of XML to structure data because XML is a standard way of representing structured information. It is easy to work with, and people can easily read, write, and understand XML without the need of any specialized skills. The XML standard is widely accepted and used in server communications such as Simple Object Access Protocol (SOAP) based web services. XML stands for eXtensible Markup Language. The XML standard specification is available at http://www.w3.org/XML/.

Adobe Flex provides a standardized ECMAScript-based set of API classes and functionality for working with XML data. This collection of classes and functionality provided by Flex are known as E4X. You can use these classes provided by Flex to build sophisticated Rich Internet Applications using XML data.

XML basics

XML is a standard way to represent categorized data into a tree structure similar to HTML documents. XML is written in plain-text format, and hence it is very easy to read, write, and manipulate its data.

A typical XML document looks like this:

<book>
   <title>Flex 3 with Java</title>
   <author>Satish Kore</author>
   <publisher>Packt Publishing</publisher>
   <pages>300</pages>
</book>

Generally, XML data is known as XML documents and it is represented by tags wrapped in angle brackets (< >). These tags are also known as XML elements. Every XML document starts with a single top-level element known as the root element. Each element is distinguished by a set of tags known as the opening tag and the closing tag. In the previous XML document, <book> is the opening tag and </book> is the closing tag. If an element contains no content, it can be written as an empty statement (also called self-closing statement). For example, <book/> is as good as writing <book></book>.

XML documents can also be more complex with nested tags and attributes, as shown in the following example:

<book ISBN="978-1-847195-34-0">
  <title>Flex 3 with Java</title>
  <author country="India" numberOfBooks="1">
   <firstName>Satish</firstName>
   <lastName>Kore</lastName>
</author>
  <publisher country="United Kingdom">Packt Publishing</publisher>
  <pages>300</pages>
</book>

Notice that the above XML document contains nested tags such as <firstName> and <lastName> under the <author> tag. ISBN, country, and numberOfBooks, which you can see inside the tags, are called XML attributes.

To learn more about XML, visit the W3Schools' XML Tutorial at http://w3schools.com/xml/.

Understanding E4X

Flex provides a set of API classes and functionality based on the ECMAScript for XML (E4X) standards in order to work with XML data. The E4X approach provides a simple and straightforward way to work with XML structured data, and it also reduces the complexity of parsing XML documents.

Earlier versions of Flex did not have a direct way of working with XML data. The E4X provides an alternative to DOM (Document Object Model) interface that uses a simpler syntax for reading and querying XML documents. More information about other E4X implementations can be found at http://en.wikipedia.org/wiki/E4X.

The key features of E4X include:

  • It is based on standard scripting language specifications known as ECMAScript for XML. Flex implements these specifications in the form of API classes and functionality for simplifying the XML data processing.
  • It provides easy and well-known operators, such as the dot (.) and @, to work with XML objects.
  • The @ and dot (.) operators can be used not only to read data, but also to assign data to XML nodes, attributes, and so on.
  • The E4X functionality is much easier and more intuitive than working with the DOM documents to access XML data.

ActionScript 3.0 includes the following E4X classes: XML, XMLList, QName, and Namespace. These classes are designed to simplify XML data processing into Flex applications.

Let's see one quick example:

Define a variable of type XML and create a sample XML document. In this example, we will assign it as a literal. However, in the real world, your application might load XML data from external sources, such as a web service or an RSS feed.

private var myBooks:XML =
  <books publisher="Packt Pub">
   <book title="Book1" price="99.99">
   <author>Author1</author>
   </book>
   <book title="Book2" price="59.99">
   <author>Author2</author>
   </book>
   <book title="Book3" price="49.99">
   <author>Author3</author>
   </book>
</books>;

Now, we will see some of the E4X approaches to read and parse the above XML in our application. The E4X uses many operators to simplify accessing XML nodes and attributes, such as dot (.) and attribute identifier (@), for accessing properties and attributes.

private function traceXML():void {
   trace(myBooks.book.(@price < 50.99).@title); //Output: Book3
   trace(myBooks.book[1].author); //Output: Author2
   trace(myBooks.@publisher); //Output: Packt Pub
   //Following for loop outputs prices of all books
   for each(var price in myBooks..@price) {
   trace(price);
   }
}

In the code above, we are using a conditional expression to extract the title of the book(s) whose price is set below 50.99$ in the first trace statement. If we have to do this manually, imagine how much code would have been needed to parse the XML. In the second trace, we are accessing a book node using index and printing its author node's value. And in the third trace, we are simply printing the root node's publisher attribute value and finally, we are using a for loop to traverse through prices of all the books and printing each price.

The following is a list of XML operators:

Operator

Name

Description

   @

 

attribute identifier

Identifies attributes of an XML or XMLList object.

 

  { }

 

 

braces(XML)

Evaluates an expression that is used in an XML or XMLList initializer.

  [ ]

 

 

brackets(XML)

Accesses a property or attribute of an XML or XMLList object, for example myBooks.book["@title"].

 

  +

concatenation(XMLList)

Concatenates (combines) XML or XMLList values into an XMLList object.

 

  +=

concatenation assignment (XMLList)

Assigns expression1

The XML object

An XML class represents an XML element, attribute, comment, processing instruction, or a text element.

We have used the XML class in our example above to initialize the myBooks variable with an XML literal. The XML class is included into an ActionScript 3.0 core class, so you don't need to import a package to use it.

The XML class provides many properties and methods to simplify XML processing, such as ignoreWhitespace and ignoreComments properties, used for ignoring whitespaces and comments in XML documents respectively. You can use the prependChild() and appendChild() methods to prepend and append XML nodes to existing XML documents. Methods such as toString() and toXMLString() allow you to convert XML to a string.

An example of an XML object:

private var myBooks:XML =
<books publisher="Packt Pub">
<book title="Book1" price="99.99">
<author>Author1</author>
</book>
<book title="Book2" price="120.00">
<author>Author2</author>
</book>
</books>;

In the above example, we have created an XML object by assigning an XML literal to it. You can also create an XML object from a string that contains XML data, as shown in the following example:

private var str:String = "<books publisher="Packt Pub"> <book title="Book1" price="99.99">
<author>Author1</author> </book>
<book title="Book2" price="59.99"> <author>Author2</author> </book> </books>";
private var myBooks:XML = new XML(str);
trace(myBooks.toXMLString()); //outputs formatted xml as string

If the XML data in string is not well-formed (for example, a closing tag is missing), then you will see a runtime error.

You can also use binding expressions in the XML text to extract contents from a variable data. For example, you could bind a node's name attribute to a variable value, as in the following line:

private var title:String = "Book1"
var aBook:XML = <book title="{title}">;

To read more about XML class methods and properties, go through Flex 3 LiveDocs at http://livedocs.adobe.com/flex/3/langref/XML.html.

The XMLList object

As the class name indicates, XMLList contains one or more XML objects. It can contain full XML documents, XML fragments, or the results of an XML query.

You can typically use all of the XML class's methods and properties on the objects from XMLList. To access these objects from the XMLList collection, iterate over it using a for each… statement.

The XMLList provides you with the following methods to work with its objects:

  • child(): Returns a specified child of every XML object
  • children(): Returns specified children of every XML object
  • descendants(): Returns all descendants of an XML object
  • elements(): Calls the elements() method of each XML object in the XMLList. Returns all elements of the XML object
  • parent(): Returns the parent of the XMLList object if all items in the XMLList object have the same parent
  • attribute(attributeName): Calls the attribute() method of each XML object and returns an XMLList object of the results. The results match the given attributeName parameter
  • attributes(): Calls the attributes() method of each XML object and returns an XMLList object of attributes for each XML object
  • contains(): Checks if the specified XML object is present in the XMLList
  • copy(): Returns a copy of the given XMLList object
  • length(): Returns the number of properties in the XMLList object
  • valueOf(): Returns the XMLList object

For details on these methods, see the ActionScript 3.0 Language Reference.

Let's return to the example of the XMLList:

var xmlList:XMLList = myBooks.book.(@price == 99.99);
var item:XML;
for each(item in xmlList)
{
trace("item:"+item.toXMLString());
}

Output:

item:<book title="Book1" price="99.99">
<author>Author1</author>
</book>

In the example above, we have used XMLList to store the result of the myBooks.book.(@price == 99.99); statement. This statement returns an XMLList containing XML node(s) whose price is 99.99$.

Working with XML objects

The XML class provides many useful methods to work with XML objects, such as the appendChild() and prependChild() methods to add an XML element to the beginning or end of an XML object, as shown in the following example:

var node1:XML = <middleInitial>B</middleInitial>
var node2:XML = <lastName>Kore</lastName>
var root:XML = <personalInfo></personalInfo>
root = root.appendChild(node1);
root = root.appendChild(node2);
root = root.prependChild(<firstName>Satish</firstName>);

The output is as follows:

<personalInfo>
<firstName>Satish</firstName>
<middleInitial>B</middleInitial>
<lastName>Kore</lastName>
</personalInfo>

You can use the insertChildBefore() or insertChildAfter() method to add a property before or after a specified property, as shown in the following example:

var x:XML = <count>
<one>1</one>
<three>3</three>
<four>4</four>
</count>;
x = x.insertChildBefore(x.three, "<two>2</two>");
x = x.insertChildAfter(x.four, "<five>5</five>");
trace(x.toXMLString());

The output of the above code is as follows:

<count>
<one>1</one>
<two>2</two>
<three>3</three>
<four>4</four>
<five>5</five>
</count>

Flex 3 with Java Develop rich internet applications quickly and easily using Adobe Flex 3, ActionScript 3.0 and integrate with a Java backend using BlazeDS 3.2
Published: June 2009
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

Using XML as dataProvider

One of the powerful features of the XML object is to use it as a dataProvider for your component that allows you to tie XML directly with your component's data model. Let's see how we can use XML as the dataProvider of a DataGrid component to display complex data.

private var xmlData:XML =
<books>
<book ISBN="184719530X">
<title>Building Websites with Joomla! 1.5</title>
<author>
<lastName>Hagen</lastName>
<firstName>Graf</firstName>
</author>
<image>../assets/images/184719530X.png</image>
<pageCount>363</pageCount>
<price>Rs.1,247.40</price>
<description>The best-selling Joomla! tutorial</description>
</book>
</books>;
private function getAuthorName(item:Object, column:DataGridColumn):String {
var xml:XML = XML(item);
return item.author.firstName +" "+ item.author.lastName;
}

We have created an XML object with a complex XML structure. Now, we will tie this with the DataGrid component using data binding, as shown in the following example:

<mx:Panel title="XML dataProvider example" width="666" height="149">
<mx:DataGrid id="dgGrid" dataProvider="{xmlData.book}"
height="100%" width="100%">
<mx:columns>
<mx:DataGridColumn headerText="ISBN" dataField="@ISBN"/>
<mx:DataGridColumn headerText="Title" dataField="title"/>
<mx:DataGridColumn headerText="Author"
labelFunction="getAuthorName"/>
<mx:DataGridColumn headerText="Price" dataField="price"/>
<mx:DataGridColumn headerText="Description"
dataField="description"/>
</mx:columns>
</mx:DataGrid>
</mx:Panel>

In the code above, we have created a DataGrid component with a set of columns to display data from the XML object. Notice that we have used {} (curly braces) to bind the XML object's specific nodes with the DataGrid. This means {xmlData.book} specifies that the DataGrid will use the book node(s) and its children nodes as source of its data.

We have used the DataGridColumn's dataField property. The dataField property is the name of the element or attribute in the XML data provider item associated with the column. For example, to display the book's title, the dataField property is set to title.

The labelFunction function is used to specify the name of a function. The function will be called and the return value is used to display in this column. For example, sometimes you might need to customize how your data gets displayed. In this case, labelFunction is used to concatenate the firstName and lastName element's values and return them as a single string.

The labelFunction function takes two parameters: the DataGrid item as an object and the DataGrid column.

The output looks as follows:

Working with XML in Flex 3 and Java-part1

You can also use the XMLListCollection object as the dataProvider of your component. The XMLListCollection object can hold the XMLList objects and provides a set of methods that lets you access, sort, filter, and modify the data items in that data object. This is very helpful if you are working with dynamic XML data. It can be used to dynamically add and remove items from the data provider and its representation in the UI control. The following example shows how to work with XMLListCollection and dynamically add new elements in it:

private var xmlData:XML =
<books>
<book ISBN="184719530X">
<title>Building Websites with Joomla! 1.5</title>
<author>
<lastName>Hagen</lastName>
<firstName>Graf</firstName>
</author>
<image>../assets/images/184719530X.png</image>
<pageCount>363</pageCount>
<price>Rs.1,247.40</price>
<description>The best-selling Joomla! tutorial</description>
</book>
</books>;
private var newBookElement:XML =
<book ISBN="1847196160">
<title>Drupal 6 JavaScript and jQuery</title>
<author>
<lastName>Matt</lastName>
<firstName>Butcher</firstName>
</author>
<image>../assets/images/1847196160.png</image>
<pageCount>250</pageCount>
<price>Rs.1,108.80</price>
<description>Drupal 6 modules and themes</description>
</book>;
private var xmlListCollection:XMLListCollection =
new XMLListCollection(xmlData.book);

Note that xmlData.book returns an XMLList object with all book elements.

You can use the addItem() method of the XMLListCollection class to add newBookElement to it, as shown here:

xmlListCollection.addItem(newBookElement);

And you can set the xmlListCollection object as the dataProvider of your DataGrid using {} (curly braces) data-binding expression.

Summary

In this article, you learned what E4X is and how to use it to work with XML data. You also learned various Flex classes to work with XML data, and use XML as a data provider.

If you have read this article you may be interested to view :

Flex 3 with Java Develop rich internet applications quickly and easily using Adobe Flex 3, ActionScript 3.0 and integrate with a Java backend using BlazeDS 3.2
Published: June 2009
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

About the Author :


Satish Kore

Satish Kore hails from Bangalore, the IT capital of India. He has more than 8 years experience in the technology world, spread across multiple technologies and domains, and he has extensive knowledge of Java, J2ME and Adobe Flex, ActionScript, and so on. He is a Principle Engineer at multinational company in Bangalore, India. He is a Flex enthusiast and evangelist and has been working on Flex since its early 1.5 version days. His application built using Flex 3 has won a best-application award from Flash-based telephony company Ribbit (http://www.ribbit.com). You can visit his blog for more information at http://blog.satishkore.com.

Books From Packt

NetBeans Platform 6.9 Developer's Guide
NetBeans Platform 6.9 Developer's Guide

JSF 2.0 Cookbook
JSF 2.0 Cookbook

Oracle JRockit: The Definitive Guide
Oracle JRockit: The Definitive Guide

Apache Maven 2 Effective Implementations: RAW
Apache Maven 2 Effective Implementations: RAW

JBoss Drools Business Rules
JBoss Drools Business Rules

GlassFish Security
GlassFish Security

iReport 3.7
iReport 3.7

Spring Security 3
Spring Security 3

No votes yet
The same node inXML by
I use an xmllist to load the whole xml after httper result event. Then i need to separate each node in a single segment, for populate the data grid. which type i use, XML or XMLList for this segments.
Correction in example by
private var title:String = "Book1" var aBook:XML = ; should be: private var title:String = "Book1" var aBook:XML = ; otherwise if you trace out @title it would just say {title}
getting xml nodes with matching attributes by
Hi Satish appreciate your time and contribution. I am looking for some method that returns all XML nodes based on attributes. like you explained above, for each(var price in myBooks..@price) { trace(price); } Is there such way in flex XML ? thanks Gopi
question by
hi Satish appreciate your work and contribution. I am trying to find if there is a way to get the list of xml nodes based on attributes? what I mean is , I shall be able to give some attributes and function should retrieve all xml nodes that are matching. similar to what you explained above : for each(var price in myBooks..@price) { trace(price); }

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
L
G
i
n
y
k
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software