Reading external XML documents. Adobe Flex, FLEX 2-PROGRAMMING ACTIONSCRIPT 3.0
광고
광고
The XML class includes the following methods for working with namespaces: addNamespace() , inScopeNamespaces() , localName() , name() , namespace() , namespaceDeclarations() , removeNamespace() , setLocalName() , setName() , and setNamespace() .
The default xml namespace directive lets you assign a default namespace for XML objects.
For example, in the following, both x1 and x2 have the same default namespace: var ns1:Namespace = new Namespace("http://www.example.com/ namespaces/"); default xml namespace = ns1; var x1:XML = <test1 />; var x2:XML = <test2 />;
XML type conversion
You can convert XML objects and XMLList objects to String values. Similarly, you can convert strings to XML objects and XMLList objects. Also, keep in mind that all XML attribute values, names, and text values are strings. The following sections discuss all these forms of XML type conversion.
Converting XML and XMLList objects to strings
The XML and XMLList classes include a toString() method and a toXMLString() method. The toXMLString() method returns a string that includes all tags, attributes, namespace declarations, and content of the XML object. For XML objects with complex content (child elements), the toString() method does exactly the same as the toXMLString() method. For XML objects with simple content (those that contain only one text element), the toString() method returns only the text content of the element, as the following example shows: var myXML:XML =
<order>
<item id='1' quantity='2'>
<menuName>burger</menuName>
<price>3.95</price>
</item>
<order>; trace(myXML.item[0].menuName.toXMLString());
// <menuName>burger</menuName> trace(myXML.item[0].menuName.toString());
// burger
328 Working with XML
If you use the trace() method without specifying toString() or toXMLString() , the data is converted using the toString() method by default, as this code shows: var myXML:XML =
<order>
<item id='1' quantity='2'>
<menuName>burger</menuName>
<price>3.95</price>
</item>
<order>; trace(myXML.item[0].menuName);
// burger
When using the trace() method to debug code, you will often want to use the toXMLString() method so that the trace() method outputs more complete data.
Converting strings to XML objects
You can use the new XML() constructor to create an XML object from a string, as follows: var x:XML = new XML("<a>test</a>");
If you attempt to convert a string to XML from a string that represents invalid XML or XML that is not well formed, a run-time error is thrown, as follows: var x:XML = new XML("<a>test"); // throws an error
Converting attribute values, names, and text values from strings
All XML attribute values, names, and text values are String data types, and you may need to convert these to other data types. For example, the following code uses the Number() function to convert text values to numbers: var myXML:XML =
<order>
<item>
<price>3.95</price>
</item>
<item>
<price>1.00</price>
</item>
</order>; var total:XML = <total>0</total>; myXML.appendChild(total); for each (var item:XML in myXML.item)
XML type conversion 329
{ myXML.total.children()[0] = Number(myXML.total.children()[0])
+ Number(item.price.children()[0]);
} trace(myXML.total); // 4.35;
If this code did not use the Number() function, the code would interpret the + operator as the string concatenation operator, and the trace() method in the last line would output the following:
01.003.95
Reading external XML documents
You can use the URLLoader class to load XML data from a URL. To use the following code in your applications, replace the XML_URL value in the example with a valid URL: var myXML:XML = new XML(); var XML_URL:String = "http://www.example.com/Sample3.xml"; var myXMLURL:URLRequest = new URLRequest(XML_URL); var myLoader:URLLoader = new URLLoader(myXMLURL); myLoader.addEventListener("complete", xmlLoaded); function xmlLoaded(evtObj:Event):void
{ myXML = XML(myLoader.data); trace("Data loaded.");
}
You can also use the XMLSocket class to set up an asynchronous XML socket connection with a server. For more information, see the ActionScript 3.0 Language Reference .
Example: Loading RSS data from the
Internet
The RSSViewer sample application shows a number of features of working with XML in
ActionScript, including the following:
■
■
Using XML methods to traverse XML data in the form of an RSS feed.
Using XML methods to assemble XML data in the form of HTML to use in a text field.
330 Working with XML
The RSS format is widely used to syndicate news via XML. A simple RSS data file may look like the following:
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
<channel>
<title>Alaska - Weather</title>
<link>http://www.nws.noaa.gov/alerts/ak.html</link>
<description>Alaska - Watches, Warnings and Advisories</description>
<item>
<title>
Short Term Forecast - Taiya Inlet, Klondike Highway (Alaska)
</title>
<link> http://www.nws.noaa.gov/alerts/ak.html#A18.AJKNK.1900
</link>
<description>
Short Term Forecast Issued At: 2005-04-11T19:00:00
Expired At: 2005-04-12T01:00:00 Issuing Weather Forecast Office
Homepage: http://pajk.arh.noaa.gov
</description>
</item>
<item>
<title>
Short Term Forecast - Haines Borough (Alaska)
</title>
<link> http://www.nws.noaa.gov/alerts/ak.html#AKZ019.AJKNOWAJK.190000
</link>
<description>
Short Term Forecast Issued At: 2005-04-11T19:00:00
Expired At: 2005-04-12T01:00:00 Issuing Weather Forecast Office
Homepage: http://pajk.arh.noaa.gov
</description>
</item>
</channel>
</rss>
The SimpleRSS application reads RSS data from the Internet, parses the data for headlines
(titles), links, and descriptions, and returns that data. The SimpleRSSUI class provides the UI and calls the SimpleRSS class, which does all of the XML processing.
Example: Loading RSS data from the Internet 331
The RSSViewer application files can be found in the folder Samples/RSSViewer. The application consists of the following files:
File Description
RSSViewer.mxml
The main application file in MXML for Flex.
com/example/programmingas3/rssViewer/
RSSParser.as
A class that contains methods that use E4X to traverse RSS (XML) data and generate a corresponding HTML representation.
RSSData/ak.rss
A sample RSS file. The application is set up to read RSS data from the web, at a Flex RSS feed hosted by Adobe. However, you can easily change the application to read RSS data from this document, which uses a slightly different schema than that of the Flex RSS feed.
Reading and parsing XML data
The RSSParser class includes an xmlLoaded() method that converts the input RSS data, stored in the rssXML variable, into an string containing HTML-formatted output, rssOutput .
Near the beginning of the method, code sets the default XML namespace if the source RSS data includes a default namespace: if (rssXML.namespace("") != undefined)
{ default xml namespace = rssXML.namespace("");
}
The next lines then loop through the contents of the source XML data, examining each descendant property named item : for each (var item:XML in rssXML..item)
{ var itemTitle:String = item.title.toString(); var itemDescription:String = item.description.toString(); var itemLink:String = item.link.toString(); outXML += buildItemHTML(itemTitle, itemDescription, itemLink);
}
The first three lines simply set string variables to represent the title, description and link properties of the item property of the XML data. The next line then calls the buildItemHTML() method to get HTML data in the form of an XMLList object, using the three new string variables as parameters.
332 Working with XML
Assembling XMLList data
The HTML data (an XMLList object) is of the following form:
<b>itemTitle</b>
<p> itemDescription
<br />
<a href="link">
<font color="#008000">More...</font>
</a>
</p>
The first lines of the method clear the default xml namespace: default xml namespace = new Namespace();
The default xml namespace directive has function block-level scope. This means that the scope of this declaration is the buildItemHTML() method.
The lines that follow assemble the XMLList, based on the string arguments passed to the function: var body:XMLList = new XMLList(); body += new XML("<b>" + itemTitle + "</b>"); var p:XML = new XML("<p>" + itemDescription + "</p>"); var link:XML = <a></a>; link.@href = itemLink; // <link href="itemLinkString"></link> link.font.@color = "#008000";
// <font color="#008000"></font></a>
// 0x008000 = green link.font = "More..."; p.appendChild(<br/>); p.appendChild(link); body += p;
This XMLList object represents string data suitable for an ActionScript HTML text field.
The xmlLoaded() method uses the return value of the buildItemHTML() method and converts it to a string:
XML.prettyPrinting = false; rssOutput = outXML.toXMLString();
Example: Loading RSS data from the Internet 333
Extracting the title of the RSS feed and sending a custom event
The xmlLoaded() method sets a rssTitle string variable, based on information in the source
RSS XML data: rssTitle = rssXML.channel.title.toString();
Finally, the xmlLoaded() method generates an event, which notifies the application that the data is parsed and available: dataWritten = new Event("dataWritten", true);
334 Working with XML
다운로드
광고