For example, one rule says that you can’t include 8l:8+l: tags in the 8da]`: section So what type of information can you store in an XML document?. Your address book contains many differ
Trang 2Foundation XML and E4X
for Flash and Flex
Sas Jacobs
Trang 3Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham,
Tony Campbell, Gary Cornell, Jonathan Gennick,
Michelle Lowman, Matthew Moodie, Jeffrey Pepper,
Frank Pohlmann, Ben Renow-Clarke, Dominic Shakeshaft,
Matt Wade, Tom Welsh
Cover Image Designer
Corné van Dooren
Interior and Cover Designer
Kurt Krames
Manufacturing Director
Tom Debolski
Copyright © 2009 by Sas Jacobs
All rights reserved No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the
copyright owner and the publisher
ISBN-13 (pbk): 978-1-4302-1634-6
ISBN-13 (electronic): 978-1-4302-1635-3 Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1 Trademarked names may appear in this book Rather than use a trademark symbol with every occurrence of a trademarked name,
we use the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of
the trademark.
Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor, New York, NY 10013 Phone 1-800-SPRINGER, fax 201-348-4505, e-mail kn`ano)ju<olnejcan)o^i*_ki, or visit sss*olnejcankjheja*_ki For information on translations, please contact Apress directly at 2855 Telegraph Avenue, Suite 600, Berkeley, CA 94705
Phone 510-549-5930, fax 510-549-5939, e-mail ejbk<]lnaoo*_ki, or visit sss*]lnaoo*_ki.
Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use eBook versions and licenses are also available for most titles For more information, reference our Special Bulk Sales–eBook Licensing web page at
dppl6++sss*]lnaoo*_ki+ejbk+^qhgo]hao.
The information in this book is distributed on an “as is” basis, without warranty Although every precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any person or entity with respect to any loss or
damage caused or alleged to be caused directly or indirectly by the information contained in this work
The source code for this book is freely available to readers at sss*bneaj`okba`*_ki in the Downloads section.
Credits
Trang 4while I was writing it You are a beautiful person, and I miss
you very much.
Trang 5About the Author xvii
About the Technical Reviewer xix
About the Cover Image Designer xxi
Acknowledgments xxiii
Introduction xxv
Chapter 1 INTRODUCTION TO XML 1
Chapter 2 GENERATING XML CONTENT 33
Chapter 3 ACTIONSCRIPT 3.0 AND XML 65
Chapter 4 USING E4X EXPRESSIONS 97
Chapter 5 USING THE URLLOADER CLASS WITH XML DOCUMENTS 135
Chapter 6 LOADING METHODS SPECIFIC TO FLEX .169
Chapter 7 LOADING METHODS SPECIFIC TO FLASH 203
Chapter 8 MODIFYING XML CONTENT WITH ACTIONSCRIPT 3.0 233
Chapter 9 COMMUNICATING WITH THE SERVER 279
Chapter 10 CONSUMING WEB SERVICES WITH FLEX 329
Chapter 11 CONSUMING WEB SERVICES WITH FLASH 373
Chapter 12 FLASH CASE STUDY .407
Chapter 13 FLEX CASE STUDY 439
Index 480
Trang 6About the Author xvii
About the Technical Reviewer xix
About the Cover Image Designer xxi
Acknowledgments xxiii
Introduction xxv
Chapter 1 INTRODUCTION TO XML 1
What is XML? 1
Understanding XML 2
Storing information in XML documents 2
XML, in the beginning 3
An XML example 4
Why XML? 5
Simple 5
Flexible 5
Descriptive 6
Accessible 6
Independent 6
Precise 7
Free 7
Why is XML important in Flash and Flex? 7
XML as a SWF data source 7
MXML in Flex 8
ActionScript 3.0 and XML 8
XML document sections 9
Document prolog 9
XML declaration 9
Processing instructions 10
Document Type Definitions 10
Document tree 11
Whitespace 11
Namespaces 11
Trang 7Structuring XML documents 12
Elements 13
Writing elements 13
Naming elements 14
Populating elements 14
The first element 15
Attributes 15
Writing attributes 15
Naming attributes 16
Structuring attributes as elements 16
Text 16
Entities 17
Comments 17
CDATA 18
A simple XML document 18
Understanding well-formed documents 20
Element structure 21
Element nesting 21
Element closing 21
Element opening and closing tags 22
Quotes for attributes 22
Documents that aren’t well-formed 23
XML, HTML, and XHTML 24
Understanding HTML 24
How is XML different from HTML? 24
Where does XHTML fit in? 25
Understanding related recommendations 27
Understanding DTDs and XML schemas 27
Understanding XSL 29
Summary 30
Chapter 2 GENERATING XML CONTENT 33
Authoring XML documents in a text editor 34
Using text and HTML editors 34
Using XML editors 35
Using Stylus Studio 2008 XML 35
Working with Dreamweaver 41
Generating XML content from a database 43
Using a web server to generate XML content 43
Working with VB NET 44
Working with PHP 47
Working with ColdFusion 49
Generating XML from other software packages 50
Getting started with XML in Excel 2007 and Word 2007 50
Generating XML from Word 2007 51
Creating an XML document in Word using Save As 51
Creating XML content in Word by using a schema 53
Trang 8Generating XML from Excel 2007 56
Generating an XML document in Excel using Save As 56
Creating XML content in Excel using a schema 57
Creating XML content with Access 2007 59
Validation and XML content in SWF applications 61
Summary 62
Chapter 3 ACTIONSCRIPT 3.0 AND XML 65
Differences between ActionScript 2.0 and 3.0 66
XML as an ActionScript data type 67
Writing XML inline within ActionScript 67
Writing XML with the XML tag in Flex 68
Overview of the new ActionScript 3.0 classes 68
The ActionScript 3.0TIH class 68
The XMLList class 69
The XMLListCollection class 69
The QName and Namespace classes 69
Working with the XML class 69
Properties of the XML class 70
Working with XML properties in Flash 71
Working with XML properties in Flex 72
Methods of the XML class 73
Locating XML content 73
Instructions for the code samples 74
Working with attribute() and attributes() 76
Finding child elements 77
Finding descendants 77
Finding elements 78
Finding the parent element 78
Locating text 79
Finding information about XML content 80
Finding an object’s position within its parent 80
Determining content type 81
Determining the number of elements 81
Displaying the name of an element 81
Determining the type of node 81
Displaying a string representation of XML 82
Modifying XML content 82
Working with the XMLList class 83
Working with the XMLListCollection class in Flex 84
Setting up the Flex application 85
Using a function to filter an XMLListCollection 86
Sorting an XMLListCollection 88
Understanding the Namespace class 89
Understanding the QName class 91
Trang 9Chapter 4 USING E4X EXPRESSIONS 97
Understanding E4X expressions 98
Working through the examples 99
Working with Flash 100
Working with Flex 100
Using the dot operator to specify a path 101
Returning text 101
Returning an XMLList 102
Specifying an index 104
Finding the last element 105
Casting returned content 105
Using the wildcard operator (*) 106
Using the attribute operator (@) 108
Looping through attributes 108
Using the descendants operator ( ) 109
Working with filter expressions 111
Working with equality 112
Finding inequality 114
Other comparisons 114
Using AND and OR in conditions 115
Using the additive operator (+) 116
Including other ActionScript expressions 117
Assigning values 117
Simple assignment with = 118
Compound assignment with += 118
Deleting content 119
E4X in action 120
Flash example 120
Flex example 127
Summary 133
Chapter 5 USING THE URLLOADER CLASS WITH XML DOCUMENTS 135
Using the URLLoader class 136
Properties of the URLLoader class 136
Methods of the URLLoader class 137
Events of the URLLoader class 138
Limits of the URLLoader class 139
Putting it all together 139
Creating a URLLoader object 139
Making the request 139
Sending variables with the request 140
Tracking the progress of a request 141
Receiving a response 142
Detecting errors 142
Working through examples 143
Working in Flash 143
Working in Flex 146
Trang 10Updating content with the URLLoader class 154
Sending variables in a Flash application 154
Sending variables in a Flex application 158
Understanding Flash Player security 164
Understanding security sandboxes 164
Creating a cross-domain policy file 165
Writing a cross-domain policy file 165
Issues with the cross-domain policy file 166
Proxying data locally 166
Summary 167
Chapter 6 LOADING METHODS SPECIFIC TO FLEX .169
Loading external content 170
Using the <mx:HTTPService> tag 170
Properties of the <mx:HTTPService> tag 171
Methods of the <mx:HTTPService> tag 174
Events of the <mx:HTTPService> tag 174
Putting it all together 175
Creating an HTTPService request 175
Making the request 175
Sending variables with the request 176
Specifying a return type 177
Specifying a request method 177
Receiving a response 177
Using the HTTPService class 178
Properties, methods, and events of the HTTPService class 178
Putting it all together 179
Creating an HTTPService request 179
Making the request 179
Sending variables with the request 180
Specifying a return type 180
Specifying a request method 180
Receiving a response 180
Accessing loaded content 181
Accessing the lastResult property directly 181
Binding the lastResult property 181
Working through an <mx:HTTPService> tag example 182
Working through an HTTPService class example 184
Passing variables with the request 191
Using <mx:request> to send variables 191
Sending variables with the HTTPService class 194
Summary 200
Trang 11Chapter 7 LOADING METHODS SPECIFIC TO FLASH 203
Understanding the AS 2.0 data components 204
Understanding the XMLConnector 206
Displaying read-only XML content 206
Displaying updatable XML data 207
Configuring the XMLConnector 207
Using the Component Inspector 208
Creating a schema from an XML document 209
Creating a schema by adding fields 211
Understanding schema settings 211
Triggering the XMLConnector component 213
Testing for a loaded XML document 214
Working through a loading example 214
Binding XML data directly to UI components 215
Adding a binding 216
Configuring the binding 217
Working through a binding example 219
Extending the binding example 220
Using the DataSet component 223
Creating bindings with a DataSet component 224
Putting it all together 226
Summary 231
Chapter 8 MODIFYING XML CONTENT WITH ACTIONSCRIPT 3.0 233
Setting up the examples 234
Setting up the Flash examples 234
Setting up the Flex examples 234
Changing element and attribute values 235
Adding, editing, and deleting XML content 237
Using appendChild() 238
Using prependChild() 239
Copying a node 239
Inserting a child node 240
Editing content 241
Using setChildren() 242
Deleting an element 242
Modifying element names and namespaces 243
Adding a namespace 243
Removing a namespace 244
Setting the namespace 245
Changing the local element name 245
Changing the qualified element name 246
Working through a modification example 247
Working in Flash 248
Working in Flex 260
Points to note about the example 276
Summary 277
Trang 12Chapter 9 COMMUNICATING WITH THE SERVER 279
Sending data to the server 280
Structuring the file path 280
Sending the variables 281
Choosing a method 282
Choosing the format 283
Working with the URLLoader class 284
Sending variables with the URLLoader class 284
Receiving a response 285
Handling errors 286
Working through a URLLoader class example 286
Understanding the VB NET page 287
Understanding the PHP page 290
Understanding the ColdFusion page 291
Working through the Flash example 292
Working through the Flex example 298
Working with the <mx:HTTPService> element 309
Sending variables with the <mx:HTTPService> element 309
Receiving a response 311
Handling errors 312
Working through an <HTTPService> element example 312
Working with the HTTPService class in Flex 316
Sending variables with the HTTPService class 316
Receiving a response 317
Handling errors 317
Working through a HTTPService class example 318
Choosing the Flex approach 326
Summary 327
Chapter 10 CONSUMING WEB SERVICES WITH FLEX 329
Understanding web services 330
Understanding SOAP web services 330
Understanding the role of WSDL 331
Using Flex to consume a web service 333
Working with the <mx:WebService> element 333
Creating the web service request 333
Specifying the operation 334
Making the request 334
Receiving the response 335
Accessing the reply 335
Understanding the resultFormat of an operation 336
Handling errors 337
Working through a tag-based example 337
Working with the WebService class 344
Trang 13Properties of the Operation class 346
Methods of the Operation class 347
Events of the Operation class 348
Consuming a web service with ActionScript 348
Creating the web service request 348
Specifying the operation 349
Making the request 349
Receiving the response 350
Accessing the reply 350
Understanding returned data types 351
Handling errors 351
Working through a scripted example 352
Using Flex Builder to manage web services 362
Working through the Web Service Introspection wizard 363
Managing web services 365
Consuming the web service 366
Using MXML tags with the generated classes 366
Scripting the generated classes 369
Summary 371
Chapter 11 CONSUMING WEB SERVICES WITH FLASH 373
Consuming web services with the URLLoader class 374
Understanding the WSDL file 375
Using GET to consume a web service 375
Working through a GET example 377
Consuming a web service with POST 384
Working through a POST example 384
Consuming a SOAP web service with the as3webservice extension 388
Working through an as3webservice example 389
Consuming a SOAP web service with the WebServiceConnector component 393
Configuring the WebServiceConnector 393
Adding parameters 394
Determining the arguments for the operation 395
Adding parameter bindings 395
Triggering the web services call 397
Binding the results 397
Accessing the results in ActionScript 399
Viewing the Web Services panel 399
Working through a WebServiceConnector example 401
Summary 405
Chapter 12 FLASH CASE STUDY .407
Understanding Flickr 408
Applying for a Flickr key 409
Making a Flickr request 409
Trang 14Understanding the Flickr API 409
Understanding the returned photo XML document 410
Understanding the returned people XML document 410
Finding recent photos 411
Finding interesting photos 412
Searching for photos 412
Finding owner information 413
Receiving a Flickr response 413
Receiving photo information 414
Receiving person information 414
Finding the URL of a photo 414
Finding the page containing the photo 415
Building the application 416
Working through the interface 416
Setting up the application 417
Getting the recent photos list 419
Displaying a large image and title 423
Adding paging functionality 426
Making cosmetic changes to the interface 427
Viewing interesting photos 428
Searching Flickr 429
Showing owner information 430
Summary 436
Chapter 13 FLEX CASE STUDY 439
Understanding Adobe Kuler 439
Applying for a Kuler key 441
Understanding the Kuler feeds 441
Accessing an existing feed 441
Searching Kuler 442
Receiving a Kuler response 444
Building the application 446
Working through the interface 447
Setting up the application 448
Creating the custom class file 449
Getting the highest rated themes 453
Displaying the theme 458
Adding paging functionality 465
Displaying the most popular schemes 468
Searching Kuler 470
Reviewing the completed code 471
KulerLoader.as 471
ColorSwatch.mxml 474
KulerCompleted.mxml 475
Summary 478
Trang 15Sas Jacobs is a web developer and author who works with Flash,
Flex, and XML Sas has written several books on these topics and has spoken about them at conferences such as Flashforward, webDU, and FlashKit Nowadays, Sas works as a software developer in the area of e-learning, where she tries to share her passion for all things ActionScript
When she’s not working, Sas loves traveling, photography, running, and her son
Trang 16Kevin Ruse is the principal of Kevin Ruse and Associates Inc., a web and print design and
consulting firm based in Santa Clara, California Kevin has been a trainer in web development and graphic design in a variety of environments, including De Anza Community College and the University of California, Santa Cruz Kevin has also taught the staff and faculty at Stanford University and University of California, Berkeley
Kevin is an Adobe Certified Instructor and a Certified Training Partner for the Altova XML Suite
of software and the <oXygen/> XML editor He currently teaches the following languages and software: Flex, Fireworks, Flash, Dreamweaver, Photoshop, InDesign, Acrobat, Quark XPress, JavaScript, ActionScript, MXML, XML, XSLT, DTD/Schema, ColdFusion, HTML, XHTML, and CSS
Kevin is the author of Web Standards Design Guide, a college textbook He is an enthusiastic
instructor who maintains a strong belief that with patience, determination, and guidance, all individuals can reach their maximum potential
Trang 17Corné van Dooren designed the front cover image for this book
After taking a brief from friends of ED to create a new design for the Foundation series, he worked at combining technological and organic forms, with the results now appearing on this and other books’ covers
Corné spent his childhood drawing on everything at hand and then began exploring the infinite world of multimedia, and his journey
of discovery hasn’t stopped since His mantra has always been, “The only limit to multimedia is the imagination,” a saying that keeps him moving forward constantly
Corné works for many international clients, writes features for multimedia magazines, reviews and tests software, authors multimedia studies, and works on many other friends of ED books You can see more of his work at and contact him through his web site, sss*_knjar]j`kknaj*_ki
If you like Corné’s work, be sure to check out his chapter in New Masters of Photoshop: Volume 2
(friends of ED, 2004)
Trang 18Thanks again to all the people at friends of ED for your hard work in putting this book together You’re a great team and, as always, it has been a pleasure working with you.
Trang 19This book started out as an update to my first book on Flash and XML Originally, the idea was
to update the content with the changes to XML in ActionScript 3.0 However, when it came to drafting the table of contents, I realized that there was a whole audience of Flex developers who would also benefit from a book about XML and ActionScript 3.0 Hence, this book was born!
So, my plan is for this book to cater to both audiences: Flash designer/developers and Flex opers I’ve included common code approaches, as well as topics that are specific to each package I’ve tried to show readers how to achieve the same XML results in both software packages.This book is best suited to people who have limited experience in the areas of XML and ActionScript 3.0 It is really pitched at introductory level users who are keen to learn more about ActionScript 3.0 The book is purposely simple in its approach, showing how to achieve common tasks required for working with XML in Flash and Flex The Flash sections show function-based approaches, whereas the Flex sections show how to work with custom classes
devel-I hope that you find this book useful and that it whets your appetite for working with XML in your SWF applications Hopefully, you’ll find that the power and simplicity of XML will inspire you in your Flash and Flex development efforts!
Layout conventions
To keep this book as clear and easy to follow as possible, the following text conventions are used throughout:
Important words or concepts are normally highlighted on the first appearance in italics.
Code is presented in beta`)se`pdbkjp
New or changed code is normally presented in ^kh`beta`)se`pdbkjp.
Pseudo-code and variable input are written in ep]he_beta`)se`pdbkjp.
Menu commands are written in the form Menu ¢ Submenu ¢ Submenu
Where I want to draw your attention to something, I’ve highlighted it like this:
Ahem, don’t say I didn’t warn you.
Sometimes code won’t fit on a single line in a book Where this happens, I use an arrow like this: £
Pdeoeo]ranu(ranuhkjcoa_pekjkb_k`apd]podkqh`^asneppaj]hh
£kjpdao]iahejasepdkqp]^na]g*
Trang 20If you work in the web design or development area, you’ve probably heard of XML It’s the basis of all modern web sites, but how many of us actually know what it really means?
This chapter introduces XML and explains why it is such an important standard for exchanging information I’ll cover some of the basic concepts behind XML, including the rules governing the structure of XML documents I’ll also review some of the uses for XML and the reasons you might need to use it in your SWF applications You’ll see some examples of XML documents and, by the end of the chapter, have a solidunderstanding of XML and its related concepts
If you’re already familiar with XML and are comfortable generating XML ments, feel free to skip forward to Chapter 3 If not, read on! You can download the resources referred to in this chapter from dppl6++sss*bneaj`okba`*_ki
docu-What is XML?
Let’s start by answering the most basic question of all: what is XML? It’s very difficult
to provide a short answer to this question The people who invented XML, the World Wide Web Consortium (W3C), provide the following definition for XML in their glos-sary at dppl6++sss*s/*knc+PN+@KI)Harah).)?kna+chkoo]nu*dpml
INTRODUCTION TO XML
Trang 21Extensible Markup Language (XML) is an extremely simple dialect of SGML The goal is to enable generic SGML to be served, received, and processed on the Web in the way that is now possible with HTML XML has been designed for ease of implementation and for interoperability with both SGML and HTML.
I think the definition is very accurate if you already know about XML, but it doesn’t really explain XML
to a novice Let’s go back to basics and see what that definition really means
Understanding XML
XML describes a format that you can use to share information By itself, XML doesn’t do anything other than store information It’s not a programming language, so you can’t use it to create stand-aloneapplications XML simply describes information XML documents need humans or software packages
to process the information that they contain
XML stands for Extensible Markup Language, which is a little misleading, because XML is actually
a metalanguage, so you can use it to create other markup languages That’s what the word extensible means in the acronym The term markup means that the languages you create use tags to surround
or mark up text, which you’ll be familiar with if you write Extensible Hypertext Markup Language (XHTML)
In fact, XHTML is one of the languages created by XML We call XHTML a vocabulary of XML It was
created when HTML was redefined according to XML rules For example, in XHTML, all tags must be in lowercase This requirement doesn’t apply to HTML
Think about the tags you use in XHTML, such as 8l:8+l: and 8d-:8+d-: These tags mark up mation that will display on a web page You use these in a very specific way, according to some predefined rules For example, one rule says that you can’t include 8l:8+l: tags in the 8da]`: section
So what type of information can you store in an XML document?
Storing information in XML documents
XML documents work best with structured information, similar to what you would find in a database.Examples include lists of names and addresses, product catalogs, sales orders, an iTunes library—anything with a standardized format Like a database, XML documents can show hierarchical relation-ships Instead of breaking the information into tables and fields, elements and tags describe the data
By nesting tags inside each another, you can create a hierarchy of parent and child elements
Trang 22The following code block shows some sample XML elements You can see the hierarchical relationship between the elements, and the tag names describe their contents.
The code sample describes contact details, similar to what you would see in an address book Most of
us have an address book that we use to store contact information about our friends and colleagues You might have the information in a software package like Outlook or Outlook Express It might also exist on your mobile phone
Your address book contains many different names, but you store the same information about each contact: name, phone number, and address The way the information is stored depends on the soft-ware package you’ve chosen If the manufacturer changes the package or discontinues it, you’ll need
to find a new way to store information about your contacts
Transferring the information to a new software program is likely to be difficult You’ll need to export it from the first package, rearrange the contents to suit the second package, and then import the data Most software applications don’t share a standard format for contact data, although some can share information You must rely on the standards created by each company
As an alternative, you could use an XML document to store the information You could create your own tag names to describe the data Tags like 8_kjp]_p:, 8ldkja:, and 8]``naoo: would provide clear descriptions for your information Any human who read the document would be able to understand what information the document held
Because the address book XML document has a standard format, you could use it to display your contacts on a web page Web browsers contain an XML parser to process the XML content You could also print out your contacts, or even build a SWF movie in Flash or Flex to display and manage your contacts
Your friends could agree on which tags to use and share their address books with each other You could all save your contacts in the same place and use tags to determine who had contributed each entry When you use a standardized structure for storage, you have endless choices about how to work with the information
So if XML is so useful, how did it all start?
XML, in the beginning
XML has been around since 1998 It is based on Standard Generalized Markup Language (SGML),which was in turn was created out of Generalized Markup Language (GML) in the 1960s XML is actu-ally a simplified version of SGML
Trang 23The first XML recommendation was released in February 1998 Since then, XML has increased in larity and is now a worldwide standard for sharing information Human beings, databases, and many popular software packages use XML documents to store and exchange information Web services and RSS feeds also use an XML format to share content over the Internet.
popu-The W3C developed the XML specification popu-The W3C also works with other recommendations such as HTML, XHTML, and Cascading Style Sheets (CSS) Detailed information about the XML specification
is available from the W3C’s web site at dppl6++sss*s/_*knc+TIH+ The current specification is XML 1.1 (Second Edition), dated 16 August 2006 You can view this specification at dppl6++sss*s/*knc+PN+.,,2+NA?)tih ).,,2,4-6/
The W3C has also created a family of related recommendations that work together to create an independent framework for managing markup languages The other areas covered by recommen-dations include XML schemas, which describe the structure and syntax of an XML document; XML stylesheets, which allow the transformation and output of XML content; and XPath, which describes how to navigate or locate specific parts of XML documents
When it created XML, the W3C published the following goals at dppl6++sss*s/*knc+PN+NA?)tih+
oa_)knecej)ck]ls:
1. XML shall be straightforwardly usable over the Internet
2. XML shall support a wide variety of applications
3. XML shall be compatible with SGML
4. It shall be easy to write programs which process XML documents
5. The number of optional features in XML is to be kept to the absolute minimum, ideally zero
6. XML documents should be human-legible and reasonably clear
7. The XML design should be prepared quickly
8. The design of XML shall be formal and concise
9. XML documents shall be easy to create
10. Terseness in XML markup is of minimal importance
In other words, XML should be easy to use in a variety of settings, by both people and software cations The rules for XML documents should also be clear so they are easy to create
appli-An XML example
The following code block shows a simple XML document with address book data containing a singlecontact If you’ve worked with XHTML, you’ll see that the elements are written in a similar way 8;tihranoekj9-*,;:
Trang 24The information is stored between tags, and the names of these tags are descriptive—for example, 8j]ia:, 8]``naoo:, and 8ldkja: The casing of the opening and closing tags is consistent The hierar-chy within the document shows that the information relates to a single8_kjp]_p: element You can use any names for these elements, as long as you follow the rules for constructing XML documents These rules are presented in the “Structuring XML documents” and “Understanding well-formeddocuments” sections later in the chapter.
Now that you know a little more about XML, you may be wondering why it is so important and why might you want to use XML as a source of data
Why XML?
Quite simply, XML is simple, flexible, descriptive, accessible, independent, precise, and free! Let’s look
at each of these advantages of XML in turn
Simple
The rules for creating XML documents are very simple You just need a text editor or another software package capable of generating XML formatted data The only proviso is that you follow some basic rules so that the XML document is well-formed You’ll find out what this means a little later in the chapter, in the “Understanding well-formed documents” section
Reading an XML document is also simple Tag names are normally descriptive, so you can figure out what data each element contains The hierarchical structure of elements allows you to work out the relationships between each piece of information
Flexible
One key aspect of XML is its flexibility As long as you follow some simple rules, you can structure an XML document in any way you like The choice of tag names, attributes, and structures is completely flexible so you can tailor it to suit your data You can also agree on an XML vocabulary so you can share information with other people A Document Type Definition or schema describes the “gram-mar,” or rules for the language
XML documents provide data for use in different applications You can generate an XML document from a corporate software package, transform it to display on a web site using Extensible Stylesheet Language Transformations (XSLT), share it with staff on portable devices, use it to create PDF files with Extensible Stylesheet Formatting Objects (XSL-FO), and provide it to other software packages You can reuse the same data in several different settings The ability to repurpose information is one of XML’s key strengths
XSLT and XSL-FO are two related XML recommendations Both of these
recommenda-tions describe how to change or transform an XML document into a different type of
output You might use an XSLT stylesheet to create HTML or text from an XML
Trang 25docu-The way XML information displays is also flexible You can display any XML document in any XML processor, perhaps a web browser, to see the structure of elements You can also use the document
to display the following:
A printed list of summary data
A web page displaying the full details of each element
A SWF movie that allows you to search the XML content
Descriptive
Because you can choose your own tag names, an XML document becomes a description of your data
Some people call XML documents self-describing.
The hierarchy of elements means that XML documents show relationships between information in
a similar way to a database For example, the hierarchies in the address book document tell us that each contact has a name, address, and phone number, and that we can store many different contacts
Accessible
XML documents separate data from presentation, so you can have access to the information without worrying about how it displays This makes the data accessible to many different people, devices, and software packages For example, the sample address book XML document could be accessed in the following ways:
Read aloud by a screen reader
Displayed on a web site
Printed to a PDF file
Processed automatically by a software package
Viewed on a mobile phone
XML documents use Unicode for their standard character set, so you can write XML documents in any number of different languages (The Unicode standard is maintained by the Unicode Consortium; see dppl6++sss*qje_k`a*knc+.) A SWF application could offer multilingual support simply by using differ-ent XML documents with equivalent content
Independent
XML is platform- and device-independent It doesn’t matter if you view the data on a PC, Macintosh,
or handheld device The data is still the same, and people can exchange it seamlessly Programmerscan also use XML to share information between software packages that otherwise couldn’t easily com-municate with each other
You don’t need a specific software package to work with XML documents You can type the content
in just about any software package capable of receiving text You can read the document in a webbrowser, text editor, or any other XML processor XML documents can provide a text-based alternative
to database content In the case of web services, XML is an intermediary between you and someone else’s database
Trang 26XML doesn’t have “flavors” that are specific to a single web browser (like CSS), version, or operating system You don’t need to create three different versions of your XML document to handle different viewing conditions.
Precise
XML is a precise standard If you want your XML document to be read by an XML parser, it must be well-formed Documents that aren’t well-formed won’t display You’re probably wondering what
well-formed means We’ll cover that a little later, in the “Understanding well-formed documents” section.
When a schema or Document Type Definition is included within an XML document, an XML processor can validate the content to make sure that the document structure conforms to the structural rules you’ve established XML documents with schemas provide standards, so there is only one way that the data they contain can be structured and interpreted
Free
XML is a specification that isn’t owned by any company or commercial enterprise This means that it’s free to use XML—you don’t have to buy any special software or other technology In fact, most major software packages either support XML or plan to support it in the future
So why should you use XML in your Flash and Flex projects?
Why is XML important in Flash and Flex?
XML is an important tool for all web developers Many people consider XML the lingua franca of the
Internet as it provides the standard for data exchange among humans and machines in many different settings
An understanding of XML is essential for Flash and Flex developers for the following reasons:
XML is one way for Flash and Flex developers to store content that powers SWF movies
Flex uses a vocabulary of XML, called MXML, to describe interfaces
XML provides a mechanism for working with data that is disconnected from a database or the Internet
ActionScript 3.0 contains features to make working with XML much easier than in previous versions, so it’s a sound alternative to plain-text files for content
XML as a SWF data source
Storing content outside a SWF application means that clients can update their own content without needing to learn either Flash or Flex, or contact the developer each time they want to make a change.It’s also possible to provide client tools that make it easy to generate the content automatically
Trang 27There are many possible sources of external data: text files, databases, and XML documents While it’s possible to create external text files for a SWF file, it’s more practical to use an XML document, which can include the data and describe the hierarchical relationships between the data.
Although a developer or client can create an XML document by hand, it’s easier to generate the content automatically With the assistance of a web server and a server-side language like PHP, Visual Basic NET (VB NET), or ColdFusion, databases can easily generate XML content suitable for a SWFapplication You’ll see how this can be done in the next chapter In terms of security, it’s good practice
to use an XML layer between a user and database
Many software packages are capable of exporting their content in an XML format The most recent versions of Microsoft Office allow you to save Word, Excel, and Access documents using either Microsoft’s XML vocabularies or your own Using standard business tools to generate XML content allows clients to take control of their own application content
For SWF applications that need to be portable, XML is an excellent choice as a data source An XML document is usually small in file size, making it easy to include on a CD, DVD, or handheld device
MXML in Flex
In order to get the most out of Flex, developers need a good understanding of XML Flex uses an XML vocabulary called MXML to describe application interfaces MXML is a markup language that provides the same role in Flex applications as XHTML does in web pages
MXML consists of a set of tags that correspond to ActionScript 3.0 classes Because MXML is a lary of XML, it must follow the same rules and be well-formed I’ll cover this term in more detail later
vocabu-in the chapter
ActionScript 3.0 and XML
ActionScript 3.0 greatly simplifies the process of working with XML documents compared with earlier versions XML is a native data type in this version of ActionScript, making it much easier to work with
in both Flash and Flex
If you’ve worked with XML in an earlier version of ActionScript, you’ll be used to writing complicated expressions and looping through collections of nodes to locate specific information in an XML docu-ment The new process means that you can target content in an XML document by using element names instead This change is significant and makes working with XML content much easier than in earlier versions of ActionScript I have found that ActionScript 3.0 has saved me hours of develop-ment time when it comes to working with XML content You’ll find out more about the changes to ActionScript in Chapter 3
ActionScript 3.0 also includes a full implementation of the ECMAScript for XML (E4X) standard, ECMA-357 (see dppl6++sss*a_i])ejpanj]pekj]h*knc+lq^he_]pekjo+behao+A?I=)OP+A_i])/13*ldf).Because ActionScript 3.0 adheres to international standards, you can take advantage of any existing knowledge you have in this area Learning E4X means that you’ll be able to apply the same skills when working with JavaScript
Now that you appreciate why XML is important to Flash and Flex developers, let’s look more closely inside an XML document
Trang 28a bit like the 8da]`: section of an XHTML document.
The prolog consists of the following:
con-8;tihranoekj9-*,;:
The minimum information that must appear inside an XML declaration is an XML version The ing declaration uses version 1.0
preced-At the time of writing, the latest recommendation is XML 1.1 However, you should
continue to use the ranoekj9-*, attribute value for backward-compatibility with
XML processors, unless you specifically need version 1.1 For example, XML 1.1 allows
characters that can’t be used in XML 1.0 and has slightly different requirements for
namespaces.
The XML declaration can also include the aj_k`ejc and op]j`]hkja attributes The order of these attributes is important
Trang 29and Chinese need UTF-16 encoding Western European languages often use ISO 8859-1 to cope with diacritical characters, such as accent marks, that aren’t part of the English language.
Theaj_k`ejc attribute must appear after the ranoekj attribute Here are some sample declarations that include an aj_k`ejc attribute:
8;tihranoekj9-*,aj_k`ejc9QPB)4;:
8;tihranoekj9-*,aj_k`ejc9QPB)-2;:
8;tihranoekj9-*,aj_k`ejc9EOK)4415)-:
The op]j`]hkja attribute indicates whether the XML document uses external information, such as
a DTD A DTD specifies the rules about which elements and attributes to use in the XML document It also provides information about the number of times each element can appear and whether an ele-ment is required or optional
Theop]j`]hkja attribute is optional When it’s included, it must appear as the last attribute in the declaration The value op]j`]hkja9jk can’t be used when you are including an external DTD or stylesheet Here is an XML declaration that includes this attribute:
8;tihranoekj9-*,aj_k`ejc9QPB)4op]j`]hkja9uao;:
Processing instructions
The prolog can also include processing instructions (PIs) Processing instructions pass information about the XML document to other applications that may need that information in order to process the XML
Processing instructions start with the characters 8; and end with ;: You can add your own cessing instructions or have them generated automatically by software packages The first item in
pro-a processing instruction is pro-a npro-ame, cpro-alled the processing instruction tpro-arget Processing instruction
names that start with tih are reserved
One common processing instruction is the inclusion of an external XSLT stylesheet An XSLT stylesheet transforms the content of an XML document into a different structure, and I’ll cover this topic in more detail later in this chapter, in the “Understanding XSL” section A processing instruction that includes
an XSLT stylesheet must appear before the document root The following line shows how this ing instruction might be written:
process-8;tih)opuhaodaappula9patp+tohdnab9heopOpuha*toh;:
Processing instructions can also appear in other places in the XML document
Document Type Definitions
DTDs, or DOCTYPE declarations, can also appear in the prolog A DTD provides rules about the ture of elements and attributes within the XML document It explains which elements are legal in the XML document, and tells you which elements are required and which are optional In other words, a DTD provides the rules for a valid XML document and explains how the document should be constructed
Trang 30struc-The prolog can include a set of declarations about the XML document, a bit like an embedded CSS stylesheet in an XHTML document The prolog can also include a reference to an external DTD as well
as or instead of these declarations The following shows an external reference to a DTD:
The document tree starts with a document root or root element An XML document can have only one root element All of the content within the XML document must appear inside the document root In HTML documents, the 8dpih: tag is the root element This is a rule of a well-formed document
Whitespace
XML documents include whitespace so that humans can read them more easily Whitespace refers to spaces, tabs, and returns that space out the content in the document The XML specification allows you to include whitespace anywhere within an XML document except before the XML declaration
XML processors can interpret whitespace in an XML document, but many won’t
actu-ally display the spaces If whitespace is important, there are ways to force an XML
processor to display the spaces using the tih6ol]_a attribute in an element I’ll leave
you to research that topic on your own if it’s something you need to do.
Namespaces
XML documents can get very complicated One XML document can reference another XML document, and different rules may apply in each case XML documents can also summarize content from multiple sources For example, you might combine several different XML documents into one
It’s possible that an XML document will contain elements that use the same name but that come from different locations and have different meanings For example, you might use the 8p]^ha: element
as part of an XHTML reference in a document about furniture, which also needs to use a 8p]^ha:element as a description of the type of furniture
In order to overcome this problem, you can use namespaces to distinguish between elements
Namespaces associate each XML element with an owner to ensure it is unique within a document, even if there are other elements that use the same name
Trang 31You can define a namespace using the tihjo attribute within an element Each namespace usually has
a prefix that you use to identify elements belonging to that namespace You can use any prefix that you like, as long as it doesn’t start with tih and doesn’t include spaces
Here is an example of using a namespace:
You can also define a namespace without using a prefix If you do this, the namespace will apply to all
elements that don’t have a prefix or namespace defined It is referred to as the default namespace.
In an XHTML document, the 8dpih: element includes a namespace without a prefix:
You can find out more about namespaces by reading the latest recommendation at the W3C site Atthe time of writing, this was the Namespaces in XML 1.1 (Second Edition) recommendation at dppl6++sss*s/*knc+PN+tih)j]iao-1/
Structuring XML documents
XML documents contain both information and markup The information about the document appears
in the prolog, as discussed in the previous section You can divide markup into the following:
Elements
Attributes
Text
Entities
Trang 32CDATA
Let’s look at each of these items in turn, starting with elements
Elements
Each XML document contains one or more elements, and they will usually make up the bulk of the
document Elements, also called nodes, identify and mark up content At the very minimum, an XML
document will contain one element: the document root
Elements serve many functions in an XML document:
Elements mark up content The opening and closing tags surround text
Tag names provide a description of the content they mark up This gives you a clue about the purpose of the element
Elements provide information about the order of data in an XML document
The position of child elements can show their relative importance in the document
Elements show the relationships between blocks of information Like databases, they show how one piece of data relates to others
Writing elements
As in XHTML, XML tags start with a less-than sign (8) and end with a greater-than sign (:) The name
of the tag appears between these signs: 8p]cJ]ia:
Although they are often used interchangeably, the terms element and tag have
slightly different meanings A tag looks like this:
8p]c:
An element looks like this:
8p]c:Okiapatp8+p]c:
An element usually contains both an opening tag and a closing tag, as well as
the text node in between those tags.
If an element contains information or other elements, it will include both an opening and closing tag:
8p]c:8+p]c: An empty element can be written using a single tag: 8p]c+: So, 8p]cj]ia:8+p]cj]ia: is
equivalent to 8p]cj]ia+: (In XHTML, the 8eic+: and 8^n+: tags are examples of empty elements.)
As explained earlier, you can include whitespace anywhere within an XML document, so you can split elements across more than one line, as shown here:
Trang 33Naming elements
Element names must follow these rules:
Element names can start with either a letter or the underscore character They can’t start with
a number
Element names can contain any letter or number, but they can’t include spaces In addition, there cannot be a space between the opening angle bracket (8) and the element name Although it’s technically possible to include a colon (6) character in an element name, it’s not
a good idea, because colons are used when referring to namespaces
It’s best to use a meaningful name that describes the content inside the tags This element name:8bqhhJ]ia:O]oF]_k^o8+bqhhJ]ia:
is more useful than this one:
8]t^f`:O]oF]_k^o8+]t^f`:
Notice that I’ve used camel case in the first example, where I capitalize the first letter
of every word in the tag name except for the first: 8bqhhJ]ia: This naming practice is
common among developers and can help to make the name more readable.
It’s also a good idea to be careful not to add extra spaces between the tag names and the contents For example using this form:
Trang 34The family analogy continues with grandparent and grandchild elements, as well as siblings.
You can also mix the content of elements, which means they can contain text as well as child elements, as in this example:
8l]najpP]c:
Patp^aejc8_deh`P]c:i]nga`ql8+_deh`P]c:
8+l]najpP]c:
The first element
The first element in an XML document is called the root element, document root, or root node It
con-tains all the other elements in the document Each XML document can have only one root element The last tag in an XML document will almost always be the closing tag for the root element
XML is case-sensitive For example, the tags 8ldkja>kkg: and 8+ldkja^kkg: are not equivalent and can’t be used to open and close the same element This is a big difference from HTML, and one of the changes introduced with XHTML
It’s possible to modify the opening tag of an element to include an attribute
Trang 35There is no limit to the number of attributes that can appear within an element, but attributes inside the same element must have unique names When you are working with multiple attributes in an ele-ment, the order isn’t important.
Naming attributes
Attribute names follow the same naming conventions as elements: you can’t start the name with
a number, and you can’t include spaces inside the name Some attribute names are reserved, so you shouldn’t use them in your XML documents Reserved names include the following;
tih6h]jc
tih6ol]_a
tih6hejg
tih6]ppne^qpa
Notice that all of these names have the tih prefix, indicating that they’re within the XML
specifica-tion These attribute names are called qualified names You can use the unqualified versions of these
attribute names So, h]jc, ol]_a, hejg, and ]ppne^qpa would be fine
Structuring attributes as elements
You can rewrite attributes as nested elements, as follows:
Text
Text refers to the content in an XML document that is marked up by the tags Text is any nonelement information stored between opening and closing element tags In the following line, the text O]oF]_k^o is stored between the 8bqhhJ]ia: and 8+bqhhJ]ia: tags:
8bqhhJ]ia:O]oF]_k^o8+bqhhJ]ia:
Unless you specify otherwise, the text between the opening and closing tags in an element will always
be processed as if it were XML This means that special characters such as 8 and : must be replaced with the entities "hp; and "cp7 to prevent an error in the XML processor Entities are discussed in the
Trang 36next section An alternative is to use a CDATA declaration to present the information, as explained
a little later, in the “CDATA” section
Entities
Character entities are symbols that represent a single character In HTML, character entities are used for special symbols such as an ampersand ("]il7) and a nonbreaking space ("j^ol7) Table 1-1 lists the common entities that you’ll need to use
Table 1-1 Entities commonly used in XML documents
Character entities replace reserved characters in XML documents All tags start with a less-than sign,
so it would be confusing to include another one in your code, like this:
8atlnaooekj:/818+atlnaooekj:
To avoid causing an error during processing, replace the less-than sign with the entity "hp7:
8atlnaooekj:/"hp718+atlnaooekj:
Some entities use Unicode numbers You can use numbers to insert characters that you can’t type on
a keyboard or choose not to type because they conflict with an XML parser (such as 8) For example, the entity ".//7 creates the character é—an e with an acute accent The number 233 is the Unicode
number for the character é.
You can also use a decimal or hexadecimal number to refer to a character For more information about this topic, see dppl6++sss*s/*knc+PN+NA?)dpih0,+_d]noap*dpihd)1*/.1
Trang 37The following are the only requirements for comments in XML documents:
A comment can’t appear before the first line in an XML declaration
Comments can’t be nested or included within tag names
You can’t include )): inside a comment
Comments shouldn’t split tags; that is, you shouldn’t comment out just an opening or closing tag
CDATA
CDATA stands for character data CDATA blocks mark text so that it isn’t processed as XML For example, you could use CDATA for information containing characters that would confuse an XML processor, such as 8 and : Doing so means that any 8 or : character contained within the CDATAblock won’t be processed as part of a tag name
CDATA sections start with 8W?@=P= and finish with Y: The character data is contained within square bracketsW Y inside the section
Entities will display literally in a CDATA section, so you shouldn’t include them For example, if you add
"hp7 to your CDATA block, it will display the same way when the XML document is processed, rather than as a left-angle bracket character
The end of a CDATA section is marked with the YY: characters, so you can’t include these inside
Trang 38The remaining lines of the XML document contain elements The first element 8ldkja>kkg:, the ment root, contains the other elements 8_kjp]_p:, 8j]ia:, 8]``naoo:, and 8ldkja: There is a hier-archical relationship between these elements
docu-There are two 8_kjp]_p: elements They share the same parent 8ldkja>kkg: and are child nodes of
that element They are also siblings to each other The document uniquely identifies each 8_kjp]_p:element using an e` attribute
The 8_kjp]_p: element contains the 8j]ia:, 8]``naoo:, and 8ldkja: elements, and they are child elements of the 8_kjp]_p: tag The 8j]ia:, 8]``naoo:, and 8ldkja: elements are grandchildren of
the8ldkja>kkg: element
The last line of the document is a closing8+ldkja>kkg: tag, written with exactly the same tion as the first tag
capitaliza-In this document tree, the trunk of the tree is the 8ldkja>kkg: tag Branching out from that element are the 8_kjp]_p: elements Each 8_kjp]_p: element has 8j]ia:, 8]``naoo:, and 8ldkja: branches Figure 1-1 shows the relationships between the elements in the phone book XML document
Figure 1-1 The elements within the phone book XML document
Trang 39In this example, I’ve created my own element names These names are descriptive, so it’s easy to figure out what I’m describing If I want to share the rules for my phone book XML document with other people, I can create a DTD or XML schema to describe how to use the elements.
I can view this, or any other XML document, by opening it in a web browser, as browsers contain XML processors Figure 1-2 shows the ]``naoo*tih file displayed in Mozilla Firefox
Figure 1-2 An XML document opened in Firefox
You can see that Firefox adds coloring to make the document tree easier to read Most recent web browsers do this Firefox also adds minus signs so that you can collapse sections of the document.Throughout this chapter, I’ve referred to the rules for creating XML documents These rules ensure that you’ll create documents that are well-formed
Understanding well-formed documents
Correctly constructed XML documents are said to be well-formed The W3C created this term to
pro-vide rules that people and software packages must follow when constructing XML documents, and it has a specific technical meaning
Well-formed documents meet the following criteria:
The document contains one or more elements
The document contains exactly one root element, which may contain other nested elements Elements nest correctly within each another
Trang 40Each element closes properly.
Opening and closing tags have matching case
Attribute values are contained in quotes
Let’s look at each of these rules in a little more detail
Of course, this document doesn’t contain any information, so it’s not likely to be very useful
It’s more likely that you’ll create an XML document where the root element contains other elements The following listing shows an example of this structure: