<<<آموزش Xml سطح مقدماتی>>>

mshgames

Well-Known Member
به نام خدا

XML eXtensible Markup Language





2dj6re0.jpg




بعد از مدت ها گفتم یه آموزش مختصر و کامل بزارم چی بهتر از XML که واقعا مبحث شیرینیه!!!!

خوب اصلا XML مخفف اختصاری چه کلمه ای eXtensible Markup Language
که به معنی زبان علامت‌گذارى قابل بسط می باشد.

Xml چه به دردی براتون می خوره خوب فرض کنید شما یه نرم افزار توسط برنامه فلش
ساختید و توش مقداری اطلاعات ریختید مثلا همین قوانین یه دانشکده که اگه یه دانشجو
مثلا در امتحانی تقلب کنه بر اساس یه ماده مثلا ماده 32 نمره ش در اون درس .25 میشه خوب وقتی که شما این فایلو ساختید و به یه نفر دادید احتمال داره که تا چند سال بعد اون قوانین عوض بشه مثلا امکان داره که اگه دانشجویی در امتحانی تقلب کنه بر اساس همون ماده 32 نمره درسش 20 بشه و حتی به خاطر این کار تشویق هم بشه(چون کار بزرگی انجام داده) حال شما که سازنده فایلید باید اونجا باشید و فایل fla را باز کنید و اونو شروع به ویرایش کنید که اولا کار وقت گیر و طاقت فرسایی ثانیا شما همیشه اونجا نیستید و حضور ندارید تا فایلو برای اون فرد ویرایش کنید
(شما بی کار نیستید که!)
اینجاست که XML به دادتون میرسه و این مشکل رو برای شما حل میکنه.

خوب چگونگی شو من الان براتون توضیح میدم

مواد مورد نیاز برای این کار :

یک عدد نر م افزار فلش یک عدد نت پد (Notepad) و یک عدد فلش کار


ابتدا می خوایم یه فایل XML بسازیم

برای این کار برنامه نات پد را باز کرده و سپس قطعه کد زیر را درش کپی می کنیم یا می نویسیم.


کد:
[COLOR="Blue"]<mohammad>
   <shabahang> 
     <name>ali</name>
     <family>ahmady</family>
     <city>rasht</city>
     <birth>1367</birth>
     </shabahang> 
</mohammad> [/COLOR]


کد بالا رو خوب نگاه کنید در کد بالا اسم فامیل شهر و سال تولد یک نفر تعریف شده اگر هر چیز دیگه ای بخواد غیر از اینا بنویسید ساختار پایه (base) به شکل بالا می باشد (به صورت درختی)

خوب حال از منوی فایل گزینه save را انتخاب کرده و نام و نوع فایل را در کادر مربوطه مطابق شکل زیر
می نویسید mohammad.xml



2is7b5f.jpg



شما یه فایل xml به همین راحتی ایجاد کردید حال این فایلتون رو در یک فولدر با نام XML قرار بدید.


حالا باید یه کاری کنیم تا این داده هایه ما وارد نرم افزار فلش بشه برای این کار برنامه فلش را باز کرده
و در بخش لایه ها یه لایه جدید با نام code ایجاد کرده و نام لایه دیگر را matn بگذارید.


34sib8w.jpg


حال لایه متن را انتخاب کرده و 5 تا دونه دینامیک تکست توسط ابزار Text Tool (نوار ابزار سمت چپ)
ایجاد کنید سپس یکی از آنها را انتخاب کرده و در قسمت Properties و در قسمت Instance Name
نامشو بدید name



nd97bb.jpg



و سپس همین کار را برای جعبه متن دیگری انجام دهید و نامشو بزارید family و نام
جعبه متن بعدی را city و بعدی را year و آخری را error بگذارید حال لایه کد را انتخاب کرده(فریمه اولشو) و دکمه F9 کیبرد را زده و کد زیر را درش وارد کنید.

کد:
[COLOR="Green"]function sina(xml){
	if(xml){
	  ex = this.firstChild.childNodes[0].childNodes[0].firstChild.nodeValue;
      ex2= this.firstChild.childNodes[0].childNodes[1].firstChild.nodeValue;
	  ex3= this.firstChild.childNodes[0].childNodes[2].firstChild.nodeValue;
	  ex4= this.firstChild.childNodes[0].childNodes[3].firstChild.nodeValue;
	  names.text= ex;
	  family.text= ex2;
	  city.text= ex3;
	  year.text= ex4;
	  erorr.text="شد لود موفقیت با اطلاعات";
	}
	else
	erorr.text="نشد لود اطلاعات";
}[/COLOR]



توضیح کد :

ابتدا ما یه فانکشن یا تابع ایجاد می کنیم سپس توسط متد firstChild خط اول در فایله xml مون رو در ex
میریزیم (خوب به کد نگاه کنید در واقع خط سوم که همون نام ما که نوشتیم علی در ex ریخته میشه و فامیلی
احمدی نیز در ex2 ریخته میشه و به ترتیب بقیه..............)
سپس این اطلاعات رو ما در 4 دینامیک فیلدی که ساختیم میریزیم و در دینامیک فیلد آخری یه عبارت تایپ
می کنیم اگر بر اثر یه مشکل اطلاعات لود نشد در فلش در دینامیک فیلد error نوشته میشه که ( اطلاعات لود نشد) اگه که اطلاعات لود شد در دینامیک تکست error نوشته میشه که (اطلاعات با موفقیت لود شد)

همین


حال یک دکمه در محیط فلش ایجاد کرده و در قسمت کد یا اکشنش کد زیر را کپی میکنید.




کد:
[COLOR="Green"]on(release){
mydatainput = new XML();
mydatainput.ignoreWhite = true;
mydatainput.load("mohammad.xml");
mydatainput.onLoad =sina;
}[/COLOR]





توضیح کد:
زمانی که دکمه فشرده شد آبجکت xml شکل می گیرد سپس سند xml ما که نامش محمد تو فلش لود میشه
سپس میره به تابع sina که در فریم اول و اونجا عملیات شروع میشه که در بالا چگونگیشو توضیح دادم.

امیدوارم مفید بوده باشه برای دوستان.

اینم فایله fla و xml تا اگه مشکلی بود برطرفش کنید


احتمالا این آموزش ادامه داره.................

نویسنده : محمد شباهنگ

موفق باشید ( توجه داشته باشید که فایل xml و فلش باید در یک پوشه باشند همونفولدره XML که از اول درست کردیم.)
 

پیوست ها

  • Learn XML MshGames.rar
    21.3 کیلوبایت · بازدیدها: 101
آخرین ویرایش:
آخ جون XML تورو خدا باز هم ادامه بده
بگو با چي ميشه اين XML روساخت؟ من برنامه dream viewer روي كامپيوترم نصبه اما نمي دونم بايد اين كد ها رو از كجا گير بيارم؟
اصلا ايا فلش خودش نمي تونه فايل XML مورد نياز رو بسازه؟ آيا برنامه اي وجود داره كه اين كار رو به صورت اتوماتيك انجام بده؟
من چند تا كامپوننت دارم كه ميگند XML نياز دارند حالا اين فايل رو من بايد چه جوري بسازم؟ با نوت پد؟!!
اما تكليف كد ها چي ميشه؟ اون ها رو از كجا بايد گير آورد؟
 

mshgames

Well-Known Member
سلام
قدم به قدم
این آموزش یه مقدمه فعلا (این آموزشو کامل بخون و یه خورده باهاش کار کن)
موفق باشی
 

Avang2005

مدیر انجمن
دستت درد نكنه محمد جان

آموزش خوبي بود ولي حيف نميشه از طريق فلش به Xml اطلاعات اضافه كرد وگرنه خيلي عروسك بود

موفق باشيد
 

mshgames

Well-Known Member
سلام
مرسی از تذکرت کیارش جان (از بس برعکس نوشتم همش فراموش می کنم)در ضمن اگه دوستان بخوان فارسی بنویسن باید از نرم افزار فارسی استایل استفاده کنن
آره محمد جان اگه از فلش هم میشد به xml راه پیدا کرد دیگه واقعا چی میشد
بازم ممنون از نظراتتون
موفق باشید
 
نمي خواهيد ادامه بدهيد؟ من هنوز ياد نگرفتم چطوري فايل xml روبسازم واين كد ها را از كجا بياورم
 

Avang2005

مدیر انجمن
سلام دوست من

براي ساخت فايل XML از برنامه NodPad استفاده كن

موفق باشيد
 
خيلي خوب نوت پد را باز كردم بعد................؟؟؟؟؟؟؟؟؟؟؟؟؟؟
فراموش نكنيد ويندوز من هم به copy و paste مسلح هستش!!!من هم راحت مي تونم اين كد ها كه در بالا موجوده رو در نوت پد ذخيره كنم وبعد پسوند فايل ذخيره شده رو به xml تغيير بدم
اما آيا سئوال من اين بود؟
من پرسيدم كه از اول شروع كنيد مبدا اين كدها كجا هستند شما اين كدها رو از كجا مي آوريد؟ من چطور براي كامپوننت خودم xml بسازم
 
آخرین ویرایش:

Avang2005

مدیر انجمن
سلام دوست من

اينجوري كه شما سوال كرديد جواب همين بود

موفق باشيد
 

mshgames

Well-Known Member
سلام

محرم اسرار 2 شما که دوست دارید از اول شروع کنید و تشنه دانشید بفرما اینم کل مبحث XML به انگلیسی در ضمن اگه حال داشتی این مقاله رو به فارسی ترجمه ش کن و بزار تو همین انجمن تا همه دوستان بتونیم یه استفاده ای بکنیم

و در آخر من دیدم که قسمت تعداد تشکرها (از کاربران دیگر) برای شما عدد 0 درج شده دوست عزیز یه چیز بدون شما وقتی سوال می کنی و جوابتو میگیری لاحقل اون دکمه تشکر رو بزن تا اون دوستی که جوابتو داده .......... (حالا نمی خوام بگم باید حتما تشکر کنی ها ولی اگه این کارو کنی خیلی بهتره)

339qbgl.jpg



موفق باشی
محمد

محمد شباهنگ گفت:



XML is fundamental in today's internet. It can be used to replace databases (in certain circumstances) or allow users to syndicate content (very common in today's blog-enabled world).
XML (an abbreviation for "eXtensible Markup Language") is a tag based language, similar to HTML except follows a slightly stricter set of rules. XML tags must have an opening and closing tag to ensure proper nesting. That means that if you had a <p> tag it must be closed with a corresponding </p> tag (or could be closed with the shorthand form of <p />).
Flash has several different ways of sending and receiving XML in order to integrate with other languages, such as ColdFusion, PHP, Perl, ASP, Java, etc. XML packets can sent and received using the XML class by using the load, send and sendAndLoad methods or you can use Flash MX Professional 2004's new XMLConnector to send and receive packets and bind them to other components on the Stage at run-time.

[1.0] CREATING AN XML Packet
The easiest way to create an XML packet in Flash is to hardcode it directly into the Actions panel (naturally!).
کد:
var users_xml:XML = new XML();
The above code demonstrates a couple different techniques. The first technique is adding specific extensions onto the end of your variable names to provide code hints within the Flash authoring environment. In the above example you appended _xml onto the end of your variable name so now when you type in the variable name followed by a period (.) Flash will display a list of methods and properties associated with that class, which in our case is the good ol' XML class.
The second technique above is defining the variable type using strict typing. A new feature to Flash MX 2004, defining a variable's type onto the end of the variable :)XML) when defining it also provides code hinting but also enforces that the particular variable always contains that specific type of variable. Again, in our case we're setting the variable to an XML object. By adding _xml onto the variable's name, you only tell Flash that you want code hints for the XML class, Flash in no way will check or enforce that the actual contents of the variable are XML data.
One important difference between using _xml and :XML is that you only need to append :XML onto the variable when you first define the variable using the var keyword. When you use the _xml extension on your variable, it is actually part of the variable name and must be used throughout your ActionScript code.
The variable users_xml now contains a new instance of the XML class. Now you are able to load the contents of an external XML file into the variable, create an XML packet and send it to a remote page (such as a ColdFusion, PHP, ASP script) or a combination of the two. To manually populate the XML packet in Flash you can do the following:
کد:
users_xml = parseXML("<name>jen</name>");
Now if you were to trace the value of the users_xml variable within Flash you would see the following displayed in the Output window:
کد:
<name>jen</name>
The code is curretly far from exciting, so far the packet is echoed to the Output window. But tracing XML packets can be very useful down the road when you are receiving packets from other sources and are trying to debug your Flash applications. You could simply the previous code by defining the XML packet when you created the new XML object earlier. You can see the complete, yet unexciting, code below:
کد:
// create and display an XML packet.
var users_xml:XML = new XML();
users_xml.parseXML("<name>jen</name>");
trace(users_xml);
----------------------------------------------------
// same as above, but slightly condensed.
var users_xml:XML = new XML("<name>jen</name>");
trace(users_xml);
The longer, less attractive method of creating XML nodes is by using a combination of createElement, createTextNode and appendChild.
کد:
var users_xml:XML = new XML();
users_xml.appendChild(users_xml.createElement("name"));
users_xml.firstChild.appendChild(users_xml.createTextNode("jen"));
trace(users_xml);
As you can see, this method requires a bit more patience and understanding to create even a simple XML packet. The code starts by creating a new instance of the XML class to create our users_xml object. Next we append a child using the XML class' appendChild method which will create our root node with the name name. Next we use another method of the XML class, createTextNode, to create the text within the root node (in our case the simple but elegant string, jen).
As you can see, either method of creating XML elements from scratch works fine, whether you want to define the packet explicitly or use the XML class' ugly children; createElement, createTextNode and appendChild. Next you'll see how to get data out of an XML packet.

[2.0] PARSING AN XML PACKET
As fun as building XML packets went, parsing the data back out can be a lot tricker and sometimes downright intimidating. Before you can successfully parse an XML packet you need to understand the XML family and how children, parents and siblings can relate.
We already briefly mentioned a root node, that is to say the topmost node in an XML packet or tree, which in HTML terms that would commonly be your <html> tag. The <html> tag can have several children, most commonly our friends the <head> and <body> tags. XML calls the <head> and <body> tags the child nodes of the <html> tag. To further confuse the topic the <head> and <body> tags would be called sibling nodes because they are at the same level below a parent node (in this case the <html> tag). Whew!
Let's start by dissecting our previous, albeit simple, XML packet.
Extracting the value jen from the XML packet is often not immediately obvious. As shown in a previous snippet you need to use the firstChild keyword to access the value of the text node. But where it really blows your mind is where you actually to use two instances of firstChild to get the node's value, as shown below:
کد:
// create and display an XML packet.
var users_xml:XML = new XML();
users_xml.parseXML("<name>jen</name>");
trace("packet:"+users_xml);
/* traces <name>jen</name> */

trace("name:"+users_xml.firstChild.firstChild.nodeValue);
/* traces jen */
The first half of the previous code listing is identical to the code examined earlier when creating text nodes. The bottom line of the code displays the node's value by tracing users_xml.firstChild.firstChild.nodeValue. The nodeValue property is used in XML to display the results of a text node, which could have been created by manually creating an XML packet (as shown above) or by using the XML class' aptly named createTextNode method or even if you were parsing an XML packet from a source outside of Flash.
If you only used one instance of firstChild in the above code you would see that Flash outputs null in the Output window when tracing the second value. In fact, the following code demonstrates what happens if you trace different aspects of the XML tree:
کد:
trace("a:"+users_xml.firstChild.firstChild.nodeValue);
/* traces a:jen */

trace("b:"+users_xml.firstChild.nodeValue);
/* traces b:null */

trace("c:"+users_xml.nodeValue);
/* traces c:null */

trace("d:"+users_xml.firstChild);
/* traces d:<name>jen</name> */

trace("e:"+users_xml.firstChild.firstChild);
/* traces e:jen */
There you have it, the basics of XML and Flash. You have an XML object which can have child nodes and nested child nodes and you have to navigate the XML structure using a combination of firstChild and the childNodes array to access data within the XML object. A very simplified outlook, but very roughly demonstrates how to navigate trees. Because you've only seen a rediculously simple XML packet thus far you haven't needed to use the childNodes array. The following code uses a more advanced XML packet and demonstrates how to use the childNodes array to loop through each child node in the XML packet.
کد:
// create and display an XML packet.
var users_xml:XML = new XML();
users_xml.parseXML("<user> <name>jen</name> <cats>3</cats> <city>Calgary</city> </user>");
trace("packet:"+users_xml);
for (var i = 0; i<users_xml.firstChild.childNodes.length; i++) {
trace("node "+i+":"+users_xml.firstChild.childNodes[i].firstChild.nodeValue);
}

/* traces the following:
packet:<user> <name>jen</name> <cats>3</cats> <city>Calgary</city> </user>
node 0:jen
node 1:3
node 2:Calgary
*/
The XML packet above can be seen better formatted in the snippet below:
کد:
<user>
<name>jen</name>
<cats>3</cats>
<city>Calgary</city>
</user>
You can see that the XML node is a little more complex and has nested child tags as well as node values. By using a for loop we are able to loop through each of the child nodes and display their values. Because the childNodes property is an array we can loop through the array using the array's length to determine when there are no more sibling nodes.
In addition to using nodeValue there are two other properties you can use when dealing with XML: nodeName and nodeType. By using the nodeName property you can access the actual name of the node, such as name, cats or city. The other property, nodeType, is a little more obscure, it tells you which type of node it is. You will remember from earlier where we used both the createElement and createTextNode methods to create different types of XML nodes, if the node is an XML node (such as <name>) codeType returns the integer 1. If the node is a text node (such as jen) then codeType returns 3.
XML isn't limited to just tags, you can also have attributes, just like HTML. For example, in the previous code example you could have changed any of the text nodes into attributes as seen below:
کد:
<user>
<name value="jen" />
<cats value="3" />
<city value="Calgary" />
</user>
Parsing an XML packet with attributes is very similar to a packet using tags, as shown in the code below:
کد:
// create and display an XML packet.
var users_xml:XML = new XML();
users_xml.parseXML("<user><name value="jen" /><cats value="3" /><city value="Calgary" /></user>");
for (var i = 0; i<users_xml.firstChild.childNodes.length; i++) {
var thisNode:XMLNode = users_xml.firstChild.childNodes[i];
trace("node "+i+" ("+thisNode.nodeName+"):"+thisNode.attributes.value);
}

/* traces the following:
node 0 (name):jen
node 1 (cats):3
node 2 (city):Calgary
*/
Now instead of having to use an excessive number of firstChild throughout your code, you can refer to the attributes object instead using the attribute name as the key (in this case the XML packet used value.
XML packets can also be loaded, sent and parsed using Flash MX Professional 2004's new XMLConnector component which will be covered later in the tutorial.

[3.0] LOADING AN EXTERNAL XML PACKET
Perhaps the easiest way to load an XML packet from an external file or remote server is using the XML class' load or sendAndLoad methods.
کد:
var external_xml:XML = new XML();
external_xml.load("somexmlfile.xml");
external_xml.onLoad = function (success:Boolean) {
if (success) {
trace("xml loaded successfully.");
} else {
trace("xml failed to load.");
};
}
If the XML file was not found or encountered an error while trying to load/parse the XML document your would see an error similar to the following in the Output window:
کد:
xml failed to load.
Error opening URL "file:///C|/Documents%20and%20Settings/<bunch of folders>/somexmlfile.xml"
If the XML file successfully loaded into Flash you would see the text xml loaded successfully. in the Output window. The reason you have to use the onLoad method to detect when the file has finished loading into Flash is because Flash is asynchonous, meaning that Flash begins to load the XML file but doesn't pause the movie to wait for a response. Instead it begins loading the XML file and continues playing the movie. This is a very important concept to understand. If you immediately tried to access the nodes and attributes from within the XML packet before it had finished loading in, Flash would return the value undefined for many of the values which could lead to very unexpected results within your movie. By using the onLoad method to detect when the file has finished loading Flash will automatically execute the declared function for you. The function takes one optional parameter, which tells you whether the file was able to be successfully loaded and parsed or not. If you didn't check whether the XML file was able to be loaded before trying to access the XML packet your movie is likely to experience unexpected errors or possibly fail to work at all.
There is another event handler you can use besides onLoad which is onData. The onData event handler is slightly different from onLoad in that it is called after the file has been loaded into Flash but before the onLoad event handler is called. So, the general series of events is:
Call to xmlInstance.load or xmlInstance.sendAndLoad.
xmlInstance.onData event handler is called.
xmlInstance.onLoad event handler is called.
Well, actually, the above list is only partially true. There is a strange quirk that you'll see when you use both onData and onLoad together, the main quirk is that your onLoad method will never actually get called. Using onData seems to short circuit the onLoad method so you'll have to explicitly call the onLoad method, as shown below:
کد:
var external_xml:XML = new XML();
external_xml.load("somexmlfile.xml");
external_xml.onData = function(data:String) {
trace("XML packet loaded.");
trace("packet:"+data);
this.onLoad(true);
};
external_xml.onLoad = function(success:Boolean) {
if (success) {
trace("xml loaded successfully.");
} else {
trace("xml failed to load.");
}
};

/* traces the following:
XML packet loaded.
packet:<user><name value="jen" /><cats value="3" /><city value="Calgary" /></user>
xml loaded successfully.
*/
One thing that you may notice is the slight difference between the onData event handler and the onLoad event handler; onData passes the contents of the file as an attribute to the method, whereas onLoad passes a Boolean value stating whether the XML was able to be successfully loaded. You can also see in the code that you had to call the onLoad method explicitly in the onData event handler passing a value of true for success.
To fully understand the plight of Flash's superhero XML, you must understand his arch nemesis, whitespace. In HTML whitespace (spaces, tabs, carriage returns, linefeeds, etc.) is purely cosmetic and generally doesn't dictate how a page will render in a browser, but in XML and Flash whitespace can have a severe impact on how your XML will work with Flash (if at all). The following code demonstrates how adding a wee bit of whitespace causes the XML empire to crumble to the ground.
To begin, create an XML file named somexmlfile.xml and add the following XML packet (paying close attention to the tabbing and linefeeds):
کد:
<user>
<name value="jen" />
<cats value="3" />
<city value="Calgary" />
</user>
Next, create a new Flash document and save it to the same folder as the XML file listed above. In the first frame of the Flash document add the following ActionScript directly to the frame:
کد:
var external_xml:XML = new XML();
external_xml.load("somexmlfile.xml");
external_xml.onLoad = function(success:Boolean) {
if (success) {
trace("xml loaded successfully.");
trace(external_xml);
trace("number of children:"+ this.firstChild.childNodes.length);
} else {
trace("xml failed to load.");
}
};
So far, so good. Or is it? Oddly enough when you test the preceding snippet the following output is displayed in the Output window in Flash:
کد:
xml loaded successfully.
<user>

<name value="jen" />

<cats value="3" />

<city value="Calgary" />

</user>
number of children:7
Apart from the extra whitespace incurred in and around the XML packet you can plainly see that everything hit the fan and Flash thinks that there are 7 child nodes of the user node. In fact, there are only technically only three child nodes (name, cats and city). The other four phantom children seem to be, in fact, the whitespace. So, how does one thwart the evil whitespace "bug"? Simple, use the XML class' ignoreWhite property. By simply adding external_xml.ignoreWhite = true; to the above ActionScript code Flash will ignore all extraneous whitespace such as tabs, spaces and linefeeds. You can see an example of the revised code and new results below:
کد:
var external_xml:XML = new XML();
external_xml.ignoreWhite = true;
external_xml.load("somexmlfile.xml");
external_xml.onLoad = function(success:Boolean) {
// ...
};

/* traces the following:
xml loaded successfully.
<user><name value="jen" /><cats value="3" /><city value="Calgary" /></user>
number of children:3
*/
Instead of setting the ignoreWhite property for that one specific XML object you can instead set it for each XML object in your movie at once by using the following code: XML.prototype.ignoreWhite = true;.

[4.0] SENDING AN XML PACKET TO A SERVER-SIDE PAGE
Using the XML class' send or sendAndLoad methods it is possible to send an XML packet from Flash to a remote page written in a server-side language (ColdFusion, PHP, ASP, etc.) allowing you to send and retrieve data from a database or take advantage of the power of server-side languages. Imagine you had a game built in Flash. By constructing an XML packet in Flash and sending it to a server-side script it would be possible to construct a "high score" table where you could store the 10 highest scores in a database. That isn't to say that XML is the only solution for transferring data between a Flash movie and a server-side script, in fact, far from it. You could also achieve the same result several different ways, including the LoadVars class, consuming a WebService using the WebServiceConnector or XMLConnector component in Flash MX Professional 2004 or even Flash Remoting.
To send an XML packet to a server-side template you could use the following ActionScript code:
کد:
XML.prototype.ignoreWhite = true;
var packet_xml:XML = new XML("<game><name>jen</name><score>77</score></game>");
var target_xml:XML = new XML();
packet_xml.xmlDecl = "<?xml version=\"1.0\" ?>";
packet_xml.sendAndLoad("http://localhost:8500/packetfromflash.cfm", target_xml);
target_xml.onData = function(data) {
_root.myText.text = data;
};
There are several new concepts packed in to one small code listing. The first line of code sets the ignoreWhite property for each XML object at once by setting the property directly in the XML class instead of having to set each XML instance separately. Next two new XML objects are created from the XML class. The first instance, packet_xml will be used to hold the XML being sent to the remote server-side template. The second XML instance, target_xml, will hold the XML packet returned from the server. The sendAndLoad method works by sending an XML packet to a server-side template and receiving an XML packet as a response, which is different from the XML class' send method which just sends an XML packet and doesn't expect any sort of response. Each of these methods are useful in their own way but have one significant difference. The XML class' send method takes a target as a parameter which allows you to open a new browser window or replace the content in the current browser window, whereas the sendAndLoad method takes a target XML packet as a parameter which won't launch a new browser window in any way.
The next dazzling new bit of XML goodness in the previous example is the xmlDecl parameter which defines which XML declaration is used for the XML document. An XML declaration is responsible for defining which version of the XML specification is being used. For our packet we set the XML declaration to XML version 1.0. Using the xmlDecl property in Flash is similar to using the following code in your HTML documents: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> which defines the version and type of HTML being used in the HTML template. The next line in the code calls the XML object's sendAndLoad method to send the current XML object (packet_xml) to our server-side template and store the returned XML packet into a new XML object instance (target_xml).
The rest of the code is the onData method which is executed when Flash receives a response from the server-side template. We are using the onData method to dump the raw XML packet returned from our ColdFusion template into a text field on the Stage with an instance name of myText.
If you wanted to use the XML class' send method instead of sendAndLoad you could change the code to the following, which would launch the target URL in a new browser (because the example code uses a target of _blank).
کد:
XML.prototype.ignoreWhite = true;
var packet_xml:XML = new XML("<game><name>jen</name><score>77</score></game>");
packet_xml.xmlDecl = "<?xml version=\"1.0\" ?>";
packet_xml.send("http://localhost:8500/packetfromflash.cfm", "_blank");
You can see now that the code is dramatically shorter than the previous example, although now it launches a new browser window (which may or may not appear if you have a pop-up blocker installed, such as the Google Toolbar. This can be very useful if you wanted to launch a highscore table in HTML instead of Flash or display search results in HTML. The main difference is that the target_xml variable is no longer needed and is replaced with a target (in this case _blank). Other valid entries are:
_blank: A new unsized browser window.
_parent: The parent frame in a frameset.
_self (default): The current browser window.
_top: The topmost frame in a frameset.
You can also specify a custom target if you wanted to reuse the same browser. If no target is specified, the browser will use _self which could replace the currently running Flash movie with the target URL, which may not be what you want.

[5.0] RECEIVING AN XML PACKET FROM FLASH WITH COLDFUSION
If you want to try the previous few examples and are using Macromedia ColdFusion you can use the following ColdFusion code:
کد:
<--- this is ColdFusion code, not ActionScript. --->
<cfsilent>
<cfsetting enablecfoutputonly="Yes"
showdebugoutput="no">

<cfset XMLPacket = getHTTPRequestData( ).content />

<cffile action="WRITE"
file="#ExpandPath('./xmlpacket.xml')#"
output="#XMLPacket#"
addnewline="Yes" />
</cfsilent>
<cfoutput><result>1</result></cfoutput>
Explaining the code in depth is beyond the scope of this XML tutorial, but essentially what the code is doing is waiting to receive an XML packet from our Flash movie and writes the packet to a file where it can be examined manually or processed by another template/process/Flash movie. The code also returns an XML packet with a value indicating the packet was received and written successfully. Naturally you'd want to add some sort of error checking and make sure the packet was valid and was able to be successfully written to the hard-drive. The mysterious <cfsilent> tag makes sure that no output is generated between the opening and closing tags so no excessive whitespace is returned to Flash along with our packet.
By integrating your Flash documents with a server-side language, such as ColdFusion, allows you to really extend the usability and depth of your site. No longer are you limited to making movies, you can now create Rich Internet Applications (or RIAs), to use the latest buzz-word. User's scores and names can be stored in databases or information can be sent from Flash to ColdFusion allowing you to send emails from within Flash. You could also take advantage of the server-side language's ability to interact with the Operating System and use ColdFusion to grab a list of files within a directory allowing you to build a nice MP3 player which can dynamically retrieve a list of available songs on the fly without forcing you to manually update XML files on the server. Using a server-side language allows you to automate much of the trivial day-to-day tasks freeing up valuable developer time which could be better spent goofing off.

[6.0] PARSING XML IN FLASH USING THE XMLCONNECTOR
The following section only applies to people using Flash MX Professional 2004 as it uses the new XMLConnector component as well as bindings and schemas. Users without Flash Pro can still send and receive XML using the various techniques above although a lot more code is required. Next you will see how you can actually syndicate a person's blog (assuming they have a public XML file available) and display the results in a Flash form to create a crude news system. This example uses the XMLConnector component to connect to a remote XML file and display the headlines in a List component. When a user clicks on a headline a brief description will be displayed in a TextArea component. Since we're using the XMLConnector it is only possible to grab news from a single XML file. If you were using the WebServiceConnector component it would be possible to syndicate a remote Web Service at Full As A Goog which would allow you to syndicate several of their available blogs feeds and return the combined results.
Step 1: Adding the XMLConnector component to the Stage
Create a new Flash document and add a XMLConnector component on to the Stage. Since the XMLConnector component instance will not be visible once the Flash document is published it doesn't really matter where it is is placed on the Stage, or if it is even off the Stage altogether. Give the XMLConnector an instance name of xmlcon.
Step 2: Adding the List and TextArea components to the Stage
Drag an instance of the List and TextArea components on to the Stage. Give the List component an instance name of headlines_ls and the TextArea component an instance name of description_txt. Position them in roughly the same position as the image below, using your artistic talents as a guide.
Step 3: Configuring the XMLConnector compoent instance
Enter the URL to an XML file in the XMLConnector component, for our example we're using Jen's blog XML file from TrainingFromTheSource.com which is powered by Movable Type. With the XMLConnector instance selected on the Stage, enter the following URL into the URL property using either the Property Inspector or Component Inspector panel: . You could use any other blog URL or XML file you wanted, but the details may differ slightly if the XML structures are different. In the Property Inspector set the direction to receive instead of send/receive as we're only fetching the remote file and not passing any values to it.
Step 4: Importing an XML Schema
The next part is where it begins to get a bit confusing. The XMLConnector is very useful as it allows you to build complex applications without having to write much ActionScript, if any at all. The only way the XMLConnector component knows the structure of the XML file is by making you manually define the XML schema using the Schema tab in the Component Inspector panel or by making you import the XML schema from a file of sample data. Being as though we're lazy, we'll choose the path of least resistance/effort and choose to import a file and have Flash do the dirty work for us.
Before we can import the sample data, we need, well, sample data. The easiest way to do this is to download a copy of the live data, and use that as our sample data. It is important to note that even though you're downloading a copy of the most recent blog entries Flash will always fetch the most recent XML file from the URL you specified earlier, it won't use the sample data being imported. So, sample data, click *here* to open a new browser and view the remote XML file of blog entries. Save this file using File > Save As to somewhere easy to locate (such as your Desktop) and give it a filename of sampledata.xml or something easy to recognize. After the schema has been imported into Flash you can safely delete this file.
After the XML file has been saved on to your local computer, make sure the Component Inspector panel is expanded and click on the Schema tab. Near the left of this tab you'll see the Import a schema from a sample XML file button. Make sure you have the results entry selected in the pane and click on the Import schema button to bring up a file browser where you can locate the XML file you saved in the previous paragraph. Once you've selected the file click the Open button to close the Open window and import the schema. If all went well you should now see a whole bunch of new entries in the Schema tab with fun double headed arrows and happy @ symbols. With the results : XML entry still selected in the schema pane change the resd only property to true to change all the double headed arrows into single headed arrows. Congratulations, you have imported an XML schema.
Step 5: Binding the XML schema to the List and TextArea components
Now that the schema has been imported and the villagers rejoice at your beheading of the double headed arrows, you are able to bind the values from the XML file to the components on the Stage. With the XMLConnector component still selected on the Stage switch to the Bindings tab in the Component Inspector panel. Click the Add binding button near the upper left corner of the tab (looks like a + sign) to open the Add Binding window. In the Add Binding window scroll down near the bottom of the schema and select the item : Array entry and click the OK button to add the first half of a binding. You should now see results.RDF.item in the pane in the Bindins tab. With the results.RDF.item entry selected i the pane double-click on the empty cell beside the bound to row. Flash will now open the Bound To window where you can complete the binding. In the Component path pane select your List component then select dataProvider : Array entry from the Schema Locationpane. Click the OK button to complete the binding and close the window.
Add another binding for the blog description. Click the Add binding button again and this time select the description entry from the item array. Click OK to close the window and you should now see results.RDF.item.[n].description in the pane. Double-click the bound to column to open the Bound To window again and this time select the TextArea component from the Compoent path pane and select text : String from under Schema location.
Step 6: Adding a behavior to trigger loading the XML file
If you were to test the Flash movie right now you would notice that nothing happens, which makes for a fairly uninteresting tutorial. The problem is that the XMLConnector component doesn't do anything until you tell it to actually do something. There are two ways to do this, by typing a single line of ActionScript to trigger the XMLConnector component or you can add a behavior which adds the single line of code for you. It is probably faster to type the code yourself, but since we are lazy, automation rules.
Click on the main Stage so the behavior is added to Frame 1 instead of to our XMLConnector component. Make sure the Behaviors panel is open and click the Add Behavior button (again, looks like a + sign) to open the menu and add our behavior. From the menu select Data > Trigger Data Source to open the Trigger Data Source window. Select your XMLConnector component from the pane, make sure the Relative radio button is selected (it will work either way, but Relative addressing is always better than using Absolute referencing). Click OK to close the window and return to your Flash document. You should now see three (3) lines of code in the Actions panel, two of which are comments generously supplied by Macromedia and the final line of code triggers the XMLConnector.
Step 7: Testing the Flash movie and complaining that it looks "ugly"
At this point you should be able to test the Flash movie in the authoring environment by pressing Ctrl+Enter (for PC users) and see that the List component contains a bunch of entries and everything looks ugly. Clicking on the entries in the List component brings up a description in the TextArea component, but they're likely to be the same for each entry. Yeah.
A couple minor tweaks are still needed to make the crude blog interface usable. The first change is to only display the blog's title in the List component instead of a combination of the URL and every other child node in the XML packet. This is actually fairly simple, click again on the XMLConnector component and make sure the Binding tab is selected in the Component Inspector panel. Click on the results.RDF.item entry. Below the bound to row in the grid below the pane is the formatter row. Set the formatter to Rearrange Fields, and double the empty cell in the formatter options row and type label=title in the Fields Definitions text field. Click OK to close the window and return to Flash.
The last step is to modify the binding for results.RDF.item.[n].description. The description should currently be "broken" and always only display the description for the first blog entry. To fix this we can tell the description that it should show the text for the currently selected item in the List component, which again is an easy fix. With the XMLConnector component still selected on the Stage, select the results.RDF.item.[n].description entry in the Bindings tab of the Compoent Inspector panel. The problem lies in the entry for Index for 'item' row, which is set to 0 by default. Double click in the empty cell beside the Index for 'item' row to open the Bound Index window. In this window, select the List component from the left pane and select selectedIndex : Number from the right pane. Click OK to close the window and return to the Stage.
Step 8: Testing the Flash movie again and complain that it still looks "ugly"
Now if you test the movie again it should display the title in the List component and the blog entry description in the TextArea below. Congratulations, you're finished. You successfully (hopefully) managed to syndicate an external XML news feed and display the contents on the Stage without having to write a single line of ActionScript.
 
آخرین ویرایش:
واي خداي من چه متن طول ودرازي اين به چه زبونيه؟ چينيه؟ نه صبر كنيد عينكم را بزنم...........
آهان انگليسيه !!واي خدا به دور از كي تا حالا انگليسي ها هم به كامپيوتر واون هم قسمت xml اون علاقه مند شدند؟!!!!!
در هر حال من كه چيزي از اين متن نمي فهمم ولي شايد يه راهي باشه
آره خودشه دعاي از ته حلق... نه معذرت مي خوام از ته قلب!!!
يا حضرت عباس به خدا بگو در يك ثانيه زبون اين اجنبي هاي انگليسي رو به من بفهمونه..
هنوز كه هيچي نشده.......... خوب شايد بايد چشممام رو ببندم ودعا كنم .خدايا........
جانمي جان .. اما نه صبر كنيد باز هم عينكم رو بزنم... اي واي اينا كه هنوز فرنگي هستند!!!
آهان شايد از ته قلبم دعا نكردم!
 

padideh

Member
باید 40 روز چشماتو ببندی و دعا کنی بعدش درست میشه (یادت باشه تو این مدت به هیچ وجه نباید چشماتو باز کنی)
 

Avang2005

مدیر انجمن
سلام دوست من

بايد اول به متن خيره بشي بعد متن رو از چشمات دور كني مطمعن باش كارت راه ميفته :)

موفق باشيد
 

جدیدترین ارسال ها

بالا