PDA

View Full Version : XML to TextField


brendanwov
01-28-2003, 09:50 AM
I've managed to really frustrate myself trying to find a good tutorial on how to use ActionScript to grab an XML doc and place it's contents in a simple textfield.

I've gotten an XML doc in a listbox and in a combobox without any problem thanks to a number of good tutorials - however, the textfield is escaping me.

I know that simple questions are frequently answered in generalities on this board, but I would appreciate if someone could provide me a link to a tutorial on this, or a simple code example that is laying around.

I'm in a new job that requires more Flash then I've ever had to do - I'm a PHP guy. I'll learn this stuff much more quickly if I see examples.

Thanks for your help!

-b

senocular
01-28-2003, 10:10 AM
the question remains, how do you want it formatted?

brendanwov
01-28-2003, 10:16 AM
This may make my ignorance a little more transparent, but if you mean the font face, size and other attributes - I know how to do that already.

However, if you are referring to how I want the textfield displayed to the user, I would like it to closely resemble an HTML Form field.

Does that answere your question? I truly appreciate your patience.

Thanks!

-b

brendanwov
01-28-2003, 10:19 AM
Let me qualify a little further. I have a multi-line blob of text that I want to stick into a form field. It will need a verticle scroll bar.

Thanks!

-b

senocular
01-28-2003, 10:31 AM
so this isnt a question about xml but rather about just getting text into a field?

See thats whats confusing me. You said you got xml into a combobox all good and fine, but thats about 10 times more difficult then throwing some text into a field. That requires not only parsing the xml appropriately but also correctly inserting the retrieved information into the combobox where you want it. A textfield on the other hand is just TextFieldName.text = content or TextFieldVariable = content, theres not much about that. At least if you know how to extract the content from the XML which it seems you have down.

On the otherhand, if you have multiple attributes/nodes that you want specifically organized and formatted some way within your generic textField then that could require a little effort, though would be basically similar to the combo boxs deal, but just concatenating onto a string rather then individual selections.

So Im still a little unclear on what you want exactly and where the xml comes into play.

brendanwov
01-28-2003, 10:45 AM
Sorry for the confusion.

Take a look at the files I have zipped for you. There are a few XML docs and one FLA file.

There are a few combo boxes that grab informarmation from the XML docs.

I have a textfield called "TXTSendMessage" That needs to grab the data from SendMessage.xml.

I had a feeling that this was ridiculously simple, but it is still escaping me.

The only way I figured out how to do the combo box was from a very good tutorial.

I am learning, but slowly.

If you could show me how to get that XML content into the textfield I would greatly appreciate it. I'd be able to run with the rest myself.

I was unable to attach the zip file, so here is a download location. It is just a little over 100k because of the Component Library.

http://www.wovknows.com/combo_box.zip

Thanks!

-b

brendanwov
01-28-2003, 11:14 AM
You got me thinking on the right track. I tried to make this much more difficult that it was.

Here is my test file I got to work.

Thanks so much!

-b

senocular
01-28-2003, 11:31 AM
ThisSendMessageXML = new XML();
ThisSendMessageXML.ignoreWhite = true;
ThisSendMessageXML.onLoad = function(success){
if (success) TXTSendMessage.text = this.firstChild.firstChild.attributes["SendMessagesName"];
}else trace("error loading ThisSendMessageXML");
};
ThisSendMessageXML.load("./xml/SendMessages.xml");


sets the text of TXTSendMessage to the attribute "SendMessagesName" in AllSendMessages' (this's firstNode) firstNode (site). heh

edit ...didnt see that post ;)

brendanwov
01-28-2003, 11:36 AM
I love the open source community! Thanks so much for your willingness to help out!

-b

Caligldnbears
01-28-2003, 12:03 PM
Speaking of which......I have an upcoming project where I am goi ng to have to manipulate the content of XML child nodes. Is this possibe to do through just Flash or am I going to need to go through a backend (if I do it will have to be jsp).

Thanks,
Michael

senocular
01-28-2003, 12:18 PM
You can not only read XML with flash but also create and edit as well.

Caligldnbears
01-28-2003, 12:31 PM
Senocular,
Can you point me in the direction of editing XML through Flash?

I would be thrilled as can be to bypass jsp. I know how to read it in, but not sure how to edit nodes.

Thanks so much,
Michael

senocular
01-28-2003, 01:23 PM
hmm... I dont know any tutorials or anything off hand... All I can do now is suggest a search and check out Flash Help. If you cant dig up anything worthy, I can post a little walk through for ya here. People seem to think Im pretty good (http://www.kirupaforum.com/showthread.php?s=&threadid=12181) at that ;)

Caligldnbears
01-28-2003, 01:41 PM
I'll see what I can dig up again...I looked around yesterday and came up empty....off to the races again..I'll let you know if I uncover some hidden gem.

Thanks,
Michael

Caligldnbears
01-28-2003, 02:24 PM
Senocular,
I can't find anything out there as far as editing an XML child node goes,only to read a file in, which I understand fine. If you could post a lil walkthrough that would definitely rock :)

Thanks,
Michael

senocular
01-28-2003, 03:28 PM
ok ... I cant now because I have to pretend Im working until the bosses leave ;) Ill start in about 2 hrs or so (they should be gone by then) and post it when Im done.

Caligldnbears
01-28-2003, 03:33 PM
I totally understand :)....hehe and thanks again for showing me the way ;)

Michael

senocular
01-29-2003, 12:03 AM
Making and Working with XML Within Flash

XML Basics
Before making/editing XML, lets first learn what it is. That begins with understanding why XML is; why does it exist? Basically, XML was created to serve as an easily usable, readable method to format information within an basic text file. What it does is allows you to contain information (text/numbers) in a hierarchal manner. This means one bit of information can serve as a type of file folder for holding more information. In fact, you can think of XML just as that, as a text write-out of a hierarchical file system. It is NOT a script and does NOT "do" anything. It just provides information in an outlined and logically layed out manner. For more information beyond laymens terms, see:
http://www.xml.com/
http://www.w3.org/XML/

XML structure
Looking at XML, you'll notice it looks a lot like HTML. In a way, HTML is a type of XML (though it was around before XML was) but the structure is in many cases the same. Heres a simple example of an XML file:

<LETTER>
<TO>Sandy</TO>
<FROM>Joseph</FROM>
<BODY>I love you!</BODY>
</LETTER>

Its fairly easy to see what information this XML file holds and how its layed out. In the file folder metaphor, this represents a folder called LETTER which contains 3 other folders TO, FROM and BODY. Each one of those folders contains the given text. The folder TO for example has "Sandy" in it.

The XML itself is made up primarily of 2 things, Nodes and Attributes. Each one of these are containters for information, though attributes are special in that they are contained only within nodes. In the example above, each one of the 'folders' (ie LETTER, TO, etc.) are a node. Nodes, as the name suggests, are containers which can hold textual information (in Attributes) as well as have within them other nodes as seen above. Its this encapsulation which makes up the heirarchy of a XML file defining its structure.

There are no attributes in the LETTER XML example, and often attributes aren't used at all. However, they can be useful in specifying properties or little tid-bits of information within a given node. Here is an example that uses attributes:

<THURSDAY>
<MEETING TIME="10:00">
The meeting was boring. I made paper airplanes with a memo I recieved earlier.
</MEETING>
<LUNCH TIME="1:30">
John came over to talk to me. He smells funny today.
<SERVED MAINCOURSE="Steak" SIDE1="Apple" SIDE2="Mustard" DRINK="TANG" />
<SPENT MEALCARD="0" CASH="12.00" />
</LUNCH>
</THURSDAY>

MEETING, for example, contains the attribute TIME. TIME's value is 10:00. In HTML attributes would be like the href or target options within an anchor <a></a> tag. TIME just gives you a way to specify some extra information which is associated directly with that node.

This example demonstrates two other things as well. One thing is that nodes with out any child nodes, or nodes within it, can be terminated within their own tag using /> instead of re-writing the tag over again in closing tag. For example, <NODE1></NODE1> can be instead be written as <NODE1 />. This is seen with the SERVED and SPENT nodes within LUNCH. Also (the other thing), you can see how the text in the LUNCH node - "John came over to talk to me. He smells funny today." - sits pleasantly with the other nodes SERVED and SPENT. This is because that text is itself a node. Its a text node. It doesnt have any bracket tags nor any attributes or child nodes (folders in itself). All it is is just text - its a text node! :) The first example also had text nodes. "Sandy", "Jospeph" and "I love you!" were all text nodes. Non-text nodes can also be refered to as "Elements".

Hopefully, for those of you who didnt know anything or knew little about XML, this cleared some things up or gave you an idea on how to perceive XML. Next is XML in Flash :beam:

senocular
01-29-2003, 12:03 AM
XML in Flash
So whats the big deal about XML in Flash? Nothing really. Its just XML... and Flash. Flash allows you to load, interpret and edit XML information. Not only that but Flash can make XML on the fly. Theres no real secret hidden goodness to there being XML support in Flash other than that now you have an easy way to pass and use structured information to Flash via a text file. Now there have been entire books written on the subject so what Im about to say here is undoubtedly only a small part of the big picture. Though its my intent to present this information in a way that makes it easy to understand in a simplified fashion (like XML :)) but in a way which should help you get up and running and using XML in Flash fairly effortlessly directly afterwards.

XML Object
First things first. Theres Flash, and then theres XML. They are not the same thing. This may seem obvious but its something you'll have to remind yourself when you're working with XML in Flash. This is because XML in flash is not text as it is in a xml text file, rather, its a Flash Object - an XML object to be exact. This XML object is not too terribly different from any generic object you make in Flash, so dont let the fact that its an "XML" object intimidate you. Being an XML object basically means it gains some extra functions and properties that generic objects dont normally have. This XML object, however, is what contains the structure of your XML within itself - itself as a Flash object, not as text.

So lets think about how a generic Object object in flash is structured. Heres an example.

myObj = new Object(5);
myObj.myProp1 = "my first property";
myObj.myProp2 = "my second property";
myObj.myArray = new Array(1,2,3);

This makes an object with a base value of 5, giving it the properties myProp1 and myProp2, each being a text value.

trace(myObj); // traces 5
trace(myObj.myProp1); // traces "my first property"
trace(myObj.myProp2); // traces "my second property"
trace(myObj.myArray); // traces 1,2,3

no big deal right? As you should already know, objects in Flash are themselves containers for information. They contain variables/properties/methods and even other objects. Hmm this sounds familiar... SO DOES XML! So here we have a match made in heaven - XML file == Flash object. And thats what the XML object does for Flash. It takes XML data and presents it in a way to make it seem as though it were a Flash object. This makes working with XML information in Flash quite easy.

How exactly Flash translates XML into an XML object is done through the following:

The base XML object is an object containing the entire XML heirarchy beneath it
All children of any given node (including those in the base XML object itself) are contained within an Array in that object called childNodes
Each Element Node contains a property nodeName (among others) giving its name
Each Text Node contains a property nodeValue (among others) containing the text
Attributes of an Element Node object are contained with an attributes object in that node object

Lets make a basic example conversion through hardcoding an XML example into a generic Flash object. This wont be an EXACT replica of the XML object in flash, but its set up (minus some properties and methods) is similar. The XML:

<HOMENODE>
<ELEMENT1 PROPA="Hello" PROPB="Gday" />
<ELEMENT2 PROPA="Hi" PROPB="Ciao" />
Random text insert
<ELEMENT3>
More text
</ELEMENT3>
</HOMENODE>

now, translated to a Flash object:

myXML = new Object();
myXML.childNodes = new Array();

myXML.childNodes[0] = new Object();
myXML.childNodes[0].nodeName = "HOMENODE";
myXML.childNodes[0].childNodes = new Array();

myXML.childNodes[0].childNodes[0] = new Object();
myXML.childNodes[0].childNodes[0].nodeName = "ELEMENT1";
myXML.childNodes[0].childNodes[0].attributes = new Object();
myXML.childNodes[0].childNodes[0].attributes.PROPA = "Hello";
myXML.childNodes[0].childNodes[0].attributes.PROPB = "Gday";

myXML.childNodes[0].childNodes[1] = new Object();
myXML.childNodes[0].childNodes[1].nodeName = "ELEMENT2";
myXML.childNodes[0].childNodes[1].attributes = new Object();
myXML.childNodes[0].childNodes[1].attributes.PROPA = "Hi";
myXML.childNodes[0].childNodes[1].attributes.PROPB = "Ciao";

myXML.childNodes[0].childNodes[2] = new Object();
myXML.childNodes[0].childNodes[2].nodeValue = "Random text insert";

myXML.childNodes[0].childNodes[3] = new Object();
myXML.childNodes[0].childNodes[3].nodeName = "ELEMENT3";
myXML.childNodes[0].childNodes[3].childNodes = new Array();
myXML.childNodes[0].childNodes[3].childNodes[0] = new Object();
myXML.childNodes[0].childNodes[3].childNodes[0].nodeValue = "More text";


Looking at this, and how the object is structured will let you see how things are layed out in an actual XML object (though it seems much more complicated in AS form). Its important to see how nodes themselves (which are 'objects') are contained within an array of their parent object and not as a direct object within that object, ie. instead of myXML.HOMENODE.ELEMENT1 you have the progression through the childNode arrays. This is mainly for reasons of ease in terms of navigation. Only the attributes object is a direct object off of the actual node object.

The XML object itself has more properties embedded in it that those which Ive included in that AS conversion above. These include properties such as nodeType, which will tell you whether or not a node is or an XML element node or a text node, and things like firstNode, the first node in a childNodes array and nextSibling which is the next node in the array in which the current node resides. For more detail can be found in Flash help. I may use these in the next section, so if you arent already familiar with them you might want to go look check them out now, or you could always look them up when the need arises. So onward to the purpose of all of this hoopla...

senocular
01-29-2003, 12:04 AM
Creating and Editing XML in Flash
Now that you finally know what XML is and how Flash sees XML you can start taking it apart and screwing around with its structure from within Flash. If not then you cheated and skipped the previous sections and need to go back and read them ;)

Straight out, here are the methods used to make/edit your XML. We'll go through each one and see how they work.

XML Object - new XML("xml text")
XMLobj.parseXML("xml text")
XMLobj.createElement("node name")
XMLobj.createTextNode("text value")
XMLobj/XMLnode.appendChild(childNode)
XMLobj/XMLnode.insertBefore(childNode, beforeNode)
XMLobj/XMLnode.cloneNode(deep)
XMLnode.removeNode()


new XML("xml text")
Number 1 is the XML object itself, the constructor - how you make a new XML object to use in Flash. Chances are, if you've used XML in Flash, you've used this. What you might not have done was passed XML into the constructor to generate an XML object based off that XML text. Example:

my_xml = new XML("<LETTER><TO>Senocular</TO><MESSAGE>Get a life</MESSAGE></LETTER>");
trace(my_xml.firstChild.nodeName); // traces LETTER
trace(my_xml.firstChild.firstChild.nodeName); // traces TO
trace(my_xml.firstChild.firstChild.firstChild.node Value); // traces Senocular

Easy! ...next
note: using _xml at the end of your XML object name will give you code hints.

XMLobj.parseXML("xml text")
All this does is the same thing the XML object constructor does when passed XML text, but instead, it adds the XML to an already existant XML object replacing its current contents with the new.

my_xml = new XML();
my_xml.parseXML("<LETTER><TO>Senocular</TO><MESSAGE>Get a life</MESSAGE></LETTER>");
trace(my_xml.firstChild.nodeName); // traces LETTER
trace(my_xml.firstChild.firstChild.nodeName); // traces TO
trace(my_xml.firstChild.firstChild.firstChild.node Value); // traces Senocular

Again, easy. partparseXML, however, can only be used on an XML object and not used on any one specific node. So if you want to parse some XML into an existing XML object, you would need to create a new XML object, and either using the constructor method, or parseXML, load the XML in then clone in or append the results to the current XML object.

XMLobj.createElement("node name")
This one is fairly self explanatory. What this does is creates an Element (node) with the given node name. The weird and possibly confusing thing is that this does NOT place the created node into the XML object, this only creates and returns a "free floating" node with the given name which can then be inserted into an XML structure anywhere you want using appendChild(). And yes this is a method of an XML object instance and not the XML object itself.

XMLobj.createTextNode("text value")
This is just like createElement but it creates a text node instead with the given text passed in. It too returns a "free floating" node which exists no where until you put it somewhere.

XMLobj.appendChild(childNode)
Here is where all the action comes into play. What this does is adds the passed node into the current XML object. This can be used by the XML object itself or any of its nodes adding the passed node into that specific XML or node object. Example:

my_xml = new XML();
my_xml.appendChild( my_xml.createElement("PICKUP") );
my_xml.firstChild.appendChild( my_xml.createElement("TRUCK") );
trace(my_xml.toString()); // traces <PICKUP><TRUCK /></PICKUP>
my_xml.firstChild.firstChild.appendChild( my_xml.createTextNode("Drive Me!") );
trace(my_xml.toString()); // traces <PICKUP><TRUCK>Drive Me!</TRUCK></PICKUP>

So basically, what appendChild does is just tacks on the new node onto the end of the childNodes array of the given XML or node object. It then gets assimilated into the XML and becomes one with the XML object :)

XMLobj.insertBefore(childNode, beforeNode)
insertBefore is similar to appendChild, infact if the beforeNode is undefined or null, insertBefore will actually be equivalent to appendChild. insertBefore just allows you to position where you want a new node object to be placed in your childNodes array. Example:

my_xml = new XML("<BASEBALLFIELD />");
my_xml.firstChild.appendChild( my_xml.createElement("FIRSTBASE") );
my_xml.firstChild.appendChild( my_xml.createElement("THIRDBASE") );
my_xml.firstChild.insertBefore( my_xml.createElement("SECONDBASE"), my_xml.firstChild.childNodes[1] );
trace(my_xml.toString()); // traces <BASEBALLFIELD><FIRSTBASE /><SECONDBASE /><THIRDBASE /></BASEBALLFIELD>


XMLobj.cloneNode(deep)
This method takes an existing node or XML object, copies it and returns it as a new node. The deep argument determines whether or not all of the child nodes of the cloned node are also copied and cloned. If deep is true, child nodes ARE copied, if false, they are NOT copied. Example:

my_xml = new XML("<ALIENS><INVADER>SuperKiller</INVADER></ALIENS>");
my_xml.firstChild.appendChild( my_xml.firstChild.firstChild.cloneNode(true) );
my_xml.firstChild.appendChild( my_xml.firstChild.firstChild.cloneNode(false) );
trace(my_xml.toString());
// traces <ALIENS><INVADER>SuperKiller</INVADER><INVADER>SuperKiller</INVADER><INVADER /></ALIENS>

notice how the last invader doesnt have a "SuperKiller" text node in it. This is because the deep argument was false on the second clone meaning no children were copied over into the returned clone node.

XMLobj.removeNode(node)
Last but not least, removeNode. It should be pretty apparent what this method does. Its the equivalent to MovieClip.removeMovieClip, only it removes nodes instead of movieclips. This is how you get rid of unwanted nodes in your XML object or other nodes within. Example:

my_xml = new XML("<FUN /><MONEY /><FRIENDS /><TAXES />");
trace(my_xml.toString()); // traces <FUN /><MONEY /><FRIENDS /><TAXES />
my_xml.childNodes[3].removeNode();
trace(my_xml.toString()); // traces <FUN /><MONEY /><FRIENDS />


What about Attributes?
Attributes are not forgotten. They are just more "manual". The attributes object can be manually edited just as any other object in Flash. This makes them easy to work with, without having to go through other XML methods. Example:

my_xml = new XML("<FRIENDS />");
my_xml.firstChild.attributes.GIRLFRIEND = "Julie"
trace(my_xml.toString()); // traces <FRIENDS GIRLFRIEND="Julie" />
delete my_xml.firstChild.attributes.GIRLFRIEND
trace(my_xml.toString()); // traces <FRIENDS />


Now, with these tools and newly gained knowledge, you can create, edit and manage XML information directly within Flash. When dealing with serverside hosted XML, all you need to do is load the original data, manipulate it within Flash as shown above, then send your newly edited XML back to a server for an update with only minimal serverside scripting usage (only that needed to save and retrieve the XML text).

lostinbeta
01-29-2003, 12:08 AM
HOLY SHIZNIT!!!!


Ironically I was just about to start learning XML in Flash tonight, and you posted this...LOL.


Way awesome. Thanks Sen. It cleared up a lot. Still got a lot ahead of me, but damn... great start.

lostinbeta
01-29-2003, 12:29 AM
Hey Sen.... If it isn't too much trouble can you go over dynamically loading XML in for dynamic menus and such?


Only if it isn't too much trouble, I am going to look around online for tutorials on this anyway.

senocular
01-29-2003, 12:31 AM
Originally posted by lostinbeta
Hey Sen.... If it isn't too much trouble can you go over dynamically loading XML in for dynamic menus and such?


Only if it isn't too much trouble, I am going to look around online for tutorials on this anyway.

did you see the zip in the first page? That might help a little. If you dont find anything, let me know and I can whip something up... not tonight though ;) (why havent I left yet? lol)

lostinbeta
01-29-2003, 12:33 AM
Yeah, I tried the .zip file on the first page, it gave me a 404 file not found error.

senocular
01-29-2003, 12:36 AM
try this

http://userpages.umbc.edu/~tmccau1/swap/combo_box.zip

'night

:beam:

lostinbeta
01-29-2003, 12:47 AM
Goodnight Sen. Thanks again.


And the file worked.

lostinbeta
01-29-2003, 03:23 AM
Ok... I didn't look for any tutorials yet, but I created something like what I was going for just with your tutorial.


Yep, I just did what I had to do while following your excellent explanation sen. Check the .zip file to see what I came up with.


(NOTE: The font on the menu is hooge_05_53 from www.miniml.com , if you don't have it, it will look funky)



Now all I need to figure out is how to add submenus in there.

Like when it is clicked have the other stuff go down and have sublinks displayed under the main clip. Oye... I think that might be advanced for me right now, but I will try.

Caligldnbears
01-29-2003, 07:31 AM
Wow Sen....thank you for this brief overview....j/k:). This helps alot the only thing I don't understand is how to send data to an external XML file. Would I just use.....

myXML.send(http://www.kirupaforum.com/senocular.xml)

That would make sense but I just want to make sure I get it.

Thanks again for taking the time to do all this as well it's helped a ton .

Thanks,
Michael

senocular
01-29-2003, 10:51 AM
Originally posted by lostinbeta
Ok... I didn't look for any tutorials yet, but I created something like what I was going for just with your tutorial.


Yep, I just did what I had to do while following your excellent explanation sen. Check the .zip file to see what I came up with.


(NOTE: The font on the menu is hooge_05_53 from www.miniml.com , if you don't have it, it will look funky)



Now all I need to figure out is how to add submenus in there.

Like when it is clicked have the other stuff go down and have sublinks displayed under the main clip. Oye... I think that might be advanced for me right now, but I will try.

Well the hardest part there is just the handling of the menu, the information is easily translated into XML through childNodes ie:


<?xml version="1.0"?>
<MENU>
<ITEM NAME="Lostinbeta">
<SUBITEM NAME="Lostinbeta" URL="http://www.lostinbeta.com/" />
<SUBITEM NAME="Lostinbeta" URL="http://www.lostinbeta.com/" />
</ITEM>
<ITEM NAME="BWBM" URL="http://www.bwbmtransformers.com" />
<ITEM NAME="Kirupa" URL="http://www.kirupa.com/" />
<ITEM NAME="Kirupa Forum" URL="http://www.kirupaforum.com/" />
<ITEM NAME="Edwin Rosero" URL="http://www.edwinrosero.com/" />
<ITEM NAME="Donna Lopez" URL="http://www.donnalopez.com/" />
<ITEM NAME="Bit 101" URL="http://www.bit-101.com/" />
<ITEM NAME="Deviant Art" URL="http://www.deviantart.com/" />
</MENU>


getting that information is just a matter of referencing the childNodes of that main button node, just like getting the attributes, but instead getting the node, then almost repeating the process with newly created submenu buttons (the process of getting the NAME and URL at least)... Ill work on converting your example in my spare time and post it when done....

senocular
01-29-2003, 11:05 AM
Originally posted by Caligldnbears
Wow Sen....thank you for this brief overview....j/k:). This helps alot the only thing I don't understand is how to send data to an external XML file. Would I just use.....

myXML.send(http://www.kirupaforum.com/senocular.xml)

That would make sense but I just want to make sure I get it.

Thanks again for taking the time to do all this as well it's helped a ton .

Thanks,
Michael

what exactly are you trying to do? XML.send sends the xml object to a URL, usually a serverside script, as a XML document. Thats where you would most likely have a script take and save the xml to a textfile (xml file ;)) on the server or something.

If you are trying to edit an XML file on your server, then youd first load the XML into Flash, edit however you want, then send it back to a script which would replace it.

make sense?

Caligldnbears
01-29-2003, 11:09 AM
I am trying to send the data to an XML files on the server and bypass the serverside (jsp,php,asp etc.). The reason for this is that I don't what backend this will eventually be sitting on.

Is this even possible? Sounds like it's not. I was just trying to find a work around for this so I could get this part working before I find out what backend I will be using.

Make sense?

Thanks,
Michael

senocular
01-29-2003, 11:27 AM
if your changing anything permanently on the backend side, yes you need at least SOME, though probably minimal, serverside scripting. All which was explained gives you a way to minupulate and edit the XML in the Flash side of things meaning you wont have to edit it at all server-side. All youd need to do is replace the old XML with the newly (Flash-) edited XML. Typically this would only be a couple lines serverside... open/create, write, close... done.

lostinbeta
01-29-2003, 01:17 PM
Originally posted by senocular
Well the hardest part there is just the handling of the menu, the information is easily translated into XML through childNodes ie:


<?xml version="1.0"?>
<MENU>
<ITEM NAME="Lostinbeta">
<SUBITEM NAME="Lostinbeta" URL="http://www.lostinbeta.com/" />
<SUBITEM NAME="Lostinbeta" URL="http://www.lostinbeta.com/" />
</ITEM>
<ITEM NAME="BWBM" URL="http://www.bwbmtransformers.com" />
<ITEM NAME="Kirupa" URL="http://www.kirupa.com/" />
<ITEM NAME="Kirupa Forum" URL="http://www.kirupaforum.com/" />
<ITEM NAME="Edwin Rosero" URL="http://www.edwinrosero.com/" />
<ITEM NAME="Donna Lopez" URL="http://www.donnalopez.com/" />
<ITEM NAME="Bit 101" URL="http://www.bit-101.com/" />
<ITEM NAME="Deviant Art" URL="http://www.deviantart.com/" />
</MENU>


getting that information is just a matter of referencing the childNodes of that main button node, just like getting the attributes, but instead getting the node, then almost repeating the process with newly created submenu buttons (the process of getting the NAME and URL at least)... Ill work on converting your example in my spare time and post it when done....

Yeah, I already knew how to set up the XML to do that, I just am not sure how to get that working in Flash so that when a button is clicked, the ones below it slide down to reveal the sub menu buttons, then when you click another one the buttons slide back up to hide the old buttons, then the new buttons slide down.

As I said though, this might be too advanced for me right now, I might just do a typical hierachial menu.

An example file would be excellent though :beam:
















Now as for writing XML to an XML file, wouldn't that require PHP?

Caligldnbears
01-29-2003, 01:36 PM
I gotcha senocular :).....This is very straight forward. I just hacked together a quick jsp file and it works...yay!!!!!

Thanks Again for your help,
Michael

senocular
01-29-2003, 10:40 PM
Originally posted by lostinbeta

Now as for writing XML to an XML file, wouldn't that require PHP?

yeah, or some other form of server-side scripting.

...


here is an exmaple of your file menu-ized. This particular type of menu folds collapses each previously opened submenu before opening a new one... I guess thats what you more or less wanted? Anywho, the code is... hmm maybe not the easiest code in the world but it uses a type of 'onComplete' method which is good to know and understand. Its actually onClosed in the script. Its a method which poses as an onComplete method for when a certain action has finished. In this case its the method which is run when the menu closes (hense onClosed). What happens is when the menu has a submenu already open, it needs to close before it can open the new submenu (in this style of menus), so the new submenu kind of 'waits' in this onClosed function which finally gets run when the old submenu closes up. Then the new submenu is initiated and the buttons below drop to reveal it.

Well take a look anyway and see if you cant mush through it. If you have any questions, let me know.... As it exists now, it operates on one submenu, but conceivebly, you could create a recursive methid of adding submenus onto submenus for whatever heirarchy your XML contains.

lostinbeta
01-29-2003, 10:45 PM
This was exactly what I was looking for. You are the best Sen. Thank you so much!!!!


I scoped the code quickly it makes sense to me, I would have never been able to come up with it on my own honestly, but reading it I know what everything individual does, I just have to associate how it all works together. Study it and all :)

I really appreciate this man. Thanks :)

senocular
01-29-2003, 10:55 PM
cool.. I didnt FULLY comment it because I think it gets messy and unreadable with too many comments, but I did do some basic outlining comments and tried to keep each section fairly seperated without stretching out the code too much. If you want I can go through it piece by piece and explain whats going on if you cant quite put your finger on it all.

study well http://userpages.umbc.edu/~tmccau1/images/smilies/bigsmile.gif

lostinbeta
01-29-2003, 11:04 PM
Well a full explanation would definitely be helpful if you want to type it. I am pretty good with learning code on my own so if you aren't up for it then don't worry about it.


One main thing I am not sure is the onClosed. You use it the same way as onEnterFrame or onRollOver, etc. Is this an undocumented feature of AS?

senocular
01-29-2003, 11:27 PM
nope, on closed is just a normal function. I used 'on' to kind of cohear to that kind of coding style, resembling onEnterFrame, onRollOver etc. Its defined in the menu button release (myButton.onRelease) and called in the enterframe.

Basically you have your menu. Its just sitting there minding its own business. Then you click on a menu button with a submenu. This button defines the onClosed function for the mainMenu clip (which controlls all the menu movement in its onEnterFrame) and sets the offset of mainMenu to be 0. offset is the movement value. It determines the offset that the lower buttons - those below this currently opening submenu - need to travel to. Thats why its set to be relative to the number of submenus (submenu buttons), all controlled by the mainMenu onEnterFrame. With the offset at 0, this tells the menu to essentially close the menu since there is no offset there is no gap for any menu to exist. mainMenu onEnterFrame, as it moves the low menu buttons up to reach their normal position checks to see when its done (obviously). When it has finished, it calls its onClosed function. This onClosed function, as specified by the menu button, resets the offset to be the new offset for the new menu. This is the 'waiting' I was talking about before. That new offset value had to wait in the onClosed function until the menu could close. Only then could it be set to properly reveal the new menu appropriately with the new offset. After the onClosed runs, setting those new values, it then gets deleted. This is because if it still existed, it would run again when it reached the new Offset (acting like an onOpened).

so laying it out you have

click menu button.
- save new submenu offset in onClosed function
- set current offset to close menu
- when menu is closed run onClosed
- onClosed sets saved offset to open menu for new submenu
- delete onClosed
- open menu to new offset
- rince... repeat...

lostinbeta
01-29-2003, 11:37 PM
AH ok, so offset sort of acts like a trigger variable that tells the menu whether to close or open?

And the reason I asked about onClose is because the only documentation I can find on it is the xmlSocketServer.onClose() and it doesn't turn blue in Flash as a documented function would.

senocular
01-29-2003, 11:57 PM
onClose is an inbuilt flash method (for xmlSocketServer as you said) and it Does turn blue, mine is onClosed though ;)

lostinbeta
01-29-2003, 11:59 PM
I know yours in onClosed, but I was saying that the only information I could find was onClose and was for XMLSocetServer . I just worded it wrong... like I do a lot.


:cool:

senocular
01-30-2003, 12:03 AM
maybe I should have named it
DoThisWhenTheMenuIsClosed


naming can add a lot of meaning to the code... there are 'internal' meanings - words that I personally would use to describe things, which may or may not be clear to other people. Things can also get confusing with all the menu variables heh. Ill have to keep that in mind on the next thing I do :)

actually I had a request to explain setInterval so I think thats next on the list... and I might come back and get into more XML here - not just editing but loading and using - explaining that a little more since this thread so far has explained what XML is and then how its edited in Flash but not really the methods of getting it into flash (or getting out for that matter).

lostinbeta
01-30-2003, 12:05 AM
Any extra info on XML is greatly welcomed.

I am moving this thread to the Best Of Kirupa section now :)

senocular
01-30-2003, 09:19 PM
XML to and from Flash

Previously discussed was a brief explanation of what XML was and how it can be manipulated within Flash. What wasnt discussed was how exactly you get existing XML, on the server for example, into Flash in the first place. If you were adept enough to follow through with the whole XML editing broo-haha, then this should be a breeze. Otherwise it should still be fairly easy to understand as it is typically the intial steps taking in learning XML-Flash integration anyway; and the act of loading XML into flash isnt difficult to understand anyway.

XML to Flash
So youve got some XML laying around in the same directory as your flash movie and you want your flash movie to take advantage of that. What can you do? Load it in, thats what. Here are the steps to loading XML into Flash.

1) Make a new XML object
my_xml = new XML();
2) Load the XML url (where your XML file is) using the LOAD command.
my_xml.load("myXMLfile.xml");

and thats it! Give it a second or two (depending on connection speed and size of the xml file) and your XML is in Flash ready to use and manipulate! Easy enough, right? The tricky thing is the previous statement, the one starting with "Give it a second or two..." Thats where you may run into some trouble.

Scripts in Flash are run 'instantaneously' each frame they are called. Ok, not exactly, since your processor cant handle more than one instruction in any one instance (depending on how you define instance). So its not literally instantaneous but it is more or less all at once, as fast as Flash can - and thats fairly fast. The internet, or even harddrives for that matter, arent quite as fast, and at times can be downright slow, espeically those poor saps still on modems (such as myself). What that means is in any one block of code, if you attempt to load in anything from an external file, such as an XML file, there will be a delay before you can actually access information from that file. For example. Lets say you have a simple XML file called 'info.xml' that has the following
<INFO NUMBER="5">
In loading that file into Flash, there will be a dealy before it is actually within and referencable from Flash in actionscript. Consider the following
my_xml = new XML();
my_xml.load("info.xml");
trace(my_xml.toString());
the trace will be blank because the info.xml file hasnt had time to actually be loaded into Flash. Fear not, there are ways around this. The best one is through using xml.onLoad.

What onLoad is, is a function which gets run by an XML object after that XML object has fully loaded whatever external XML file it was instructed to load and has been able to parse (or understand) the loaded data. This is very similar to onEnterFrame and onMouseDown events except that this event is, instead, associated with the event of XML information being fully loaded and parsed within an XML object. It is within this function which you would put whatever operations you need to be run that use your loaded XML information. For instance, to get the previous example to fully trace the string representation of the XML, you would use onLoad like so:
my_xml = new XML();
my_xml.onLoad = function(){
trace(this.toString());
}
my_xml.load("info.xml");
Now, only when "info.xml" has fully loaded will the trace be called. Note that 'this' is used within the function to represent the XML object. Thats because the scope of the function is whithin that object itself, so 'this' within that onLoad references my_xml.

Also be aware that you dont have to define onLoad itself directly as a function. You can easily set it to be an existing function by saying:
my_xml.onLoad = someOtherFunction;
and you can change onLoad at anytime, for instance if you needed a new set of operations to be associated with the loading of new XML.

Success. Something I didnt mention earlier was a special argument that gets passed to an onLoad call called 'success'. This argument is true or false depending on whether or not the XML document requested in the load call was found and successfully loaded. The success argument is true if the document was loaded successfully and false if not. Example:
my_xml = new XML();
my_xml.onLoad = function(success){
if (success){
trace(this.toString());
}else{
trace("There was an Error in loading the XML document");
}
}
my_xml.load("info.xml");
Though this argument is not necessary, it is suggested that you make full use of it to keep your actionscript aware and robust.

Something else that happens with an XML object's onLoad is the setting of an XML property - loaded. The loaded property that, on the load call is set to false and then becomes true with a successful onLoad. In essense, when the onLoad is called, the success parameter is saved into the xml object itself as the loaded property. If success is false, loaded will be false, since afterall the XML document didnt load. If there was success, loaded will be true. You can actually see this in the pre-set definition of the XML onData function as seen here:
XML.prototype.onData = function (src) {
if (src == undefined){
this.onLoad(false);
}else{
this.parseXML(src);
this.loaded = true;
this.onLoad(true);
}
}
onData is the real event that is called when the XML object has fully loaded its requested XML document. Its this function (which is defined as the above for all of your XML objects unless you specifically over-ride it by writing your own) which actually calls the onLoad function and sets the value of the XML object's loaded property. The src argument is the actual text of the XML file itself. Once that text has loaded its passed into onData (just like onData for a LoadVars object) and onData checks to see if src is defined or not. When it wont be defined is when theres an error in downloading the XML document. When thats the case, onLoad is called and passed a false (false for the success argument in onLoad). Otherwise, the XML data is parsed into the XML object so the XML object understands it, loaded is set to true and onLoad is called with a success argument of true. Chances are you'd never worry about changing or setting the onData function of your XML object since it is already made for you. All you need to do is write an onLoad to handle the XML object once the loaded XML has been fully loaded and parsed correctly into the XML object.

Also like a LoadVars object, XML objects have getBytesLoaded and getBytesTotal properties which let you check to see how much of how much of your XML document has been loaded. If your document is extremely large, you might even want to build a preloader for it ;)

One other thing you might want to be aware of in loading XML into Flash is the status property. This is like a version of loaded but for the XML parsing, not loading. This tells you any errors that might have occured in the process of parsing an XML document to be understood properly by flash. The following outlines the values status can contain and what they mean:

-0 No error; parse was completed successfully.
-2 A CDATA section was not properly terminated.
-3 The XML declaration was not properly terminated.
-4 The DOCTYPE declaration was not properly terminated.
-5 A comment was not properly terminated.
-6 An XML element was malformed.
-7 Out of memory.
-8 An attribute value was not properly terminated.
-9 A start-tag was not matched with an end-tag.
-10 An end-tag was encountered without a matching start-tag.

I personally have never used status outside of debugging, but it could be very useful for keeping your Flash movie robust, especially in dealing with possibly ignorant clients who might write flicted code for your Flash movie powerhouse ;)

senocular
01-30-2003, 10:55 PM
XML from Flash
Once you have loaded your XML into Flash, made sure it was loaded ok, made sure it parsed without a hitch, then maybe manipulated it some and called it a day, you then have the option of sending that XML back to the server from whence it came. You can have two general reasons for doing this.

to update an existing (or create a new) XML document to reside on the server
to initiate a server-side script which will read the passed data and perform an action, most likely returning data back to flash.


The Flash side of this is not so hard at all. In fact there are only 2 methods for handling this and one is more or less the other with an added feature. What could be difficult is the server-side of it all - something which I wont get into here; thats what the server-side scripting forum (http://www.kirupaforum.com/forumdisplay.php?s=&forumid=11) is for :)

Those 2 functions mentioned above are
XMLobj.send("url");
XMLobj.sendAndLoad("url", targetXMLobject);
sendAndLoad is virtually send but allows you to put the server-returned data into another XML object in Flash as though it was loaded through calling the load function of that XML object, hense "sendAndLoad" name.

For reason 1, sending XML to the server to be saved, send is most likely your method of choice. Simply, it sends the all the XML data of that XML object properly encoded to the server as text and allows whatever server-side script you put in the specified URL do its thing with that XML. With reason 1, that would be saving the XML as a file.

Reason 2 could also be used with send, but you also have here, the option to use sendAndLoad. This will send the XML data of the current XML object to the server then send the resulting XML data into the targetXMLobject to be parsed and stored there.

Both send and sendAndLoad also have optional parameters window which operates as a getURL target. The window specifies the window which the url is loaded into hense, where a browser responce can be seen. Examples:

my_xml = new XML("<NODE>Value</NODE>");
i_xml = new XML();
i_xml.onLoad = function(){
_root.output.text = this.toString();
// WARNING: when working in Flash, sent XML data is transfered through
// GET and NOT POST which can interfer with your XML handling. You may
// want to test via the server and not in the Flash authoring environment
}
my_xml.sendAndLoad("xmlScript.php", i_xml);

Note Both send and sendAndLoad normally use POST as the method of information transfer (see Warning).

... if you are unsure of your XML server-side scripting skills or have little knowlesge in working with XML server-side, you can also (which may be the easiest thing to do for Reason 1) send your XML as a string through loadVariables associating it with an identifiable variable name which can then be easily referenced and used within your script.

senocular
01-31-2003, 10:50 AM
Here is an updated XML driven menu, Ill go through its workings step by step in a following post:

lostinbeta
01-31-2003, 01:02 PM
Wow, that is excellent Sen.


Damn your skills....lol.

senocular
02-01-2003, 11:09 AM
XML Menu Example Explained

First the XML of the menu

<?xml version="1.0"?>
<MENU>
<ITEM NAME="Menu Dropdown 1">
<SUBITEM NAME="Submenu Link 1" URL="sublink11.html" />
<SUBITEM NAME="Submenu Link 2" URL="sublink11.html" />
</ITEM>
<ITEM NAME="Menu Dropdown 2">
<SUBITEM NAME="Submenu Link 1" URL="sublink21.html" />
<SUBITEM NAME="Submenu Link 2" URL="sublink22.html" />
<SUBITEM NAME="Submenu Link 3" URL="sublink23.html" />
<SUBITEM NAME="Submenu Link 4" URL="sublink24.html" />
</ITEM>
<ITEM NAME="Menu Link 1" URL="link1.html" />
<ITEM NAME="Menu Link 2" URL="link2.html" />
<ITEM NAME="Menu Dropdown 3">
<SUBITEM NAME="Submenu Link 1" URL="sublink31.html" />
<SUBITEM NAME="Submenu Link 2" URL="sublink32.html" />
<SUBITEM NAME="Submenu Link 3" URL="sublink33.html" />
</ITEM>
<ITEM NAME="Menu Link 3" URL="link3.html" />
</MENU>


This is pretty straightforward, especially if you've been following along with the XML explanations earlier. What we have is a main XML node in the XML called MENU which contains ITEM nodes. Now of these ITEM nodes we see two variations. 1)ITEM nodes which have no children and contain NAME and URL attributes, and then there are 2) the ITEM nodes which only contain a single attribute, NAME but also contains child nodes SUBITEMs which are like the forementioned ITME nodes having the NAME and URL attributes. Essentially, theses SUBITEM nodes are the first type of ITEM nodes, they are just contined within another ITEM node. It is these SUBITEMS which make our drop-down list in the example.

In terms of what XML is, it has done its job well, making it fairly easy to simply look at this file in a text editor or even on your screen here) and see exactly what it means and will accomplish.

What we will do in Flash is read this XML in using an XML object and the load method, then, using the onload event, take this gathered information and generate (dynamically) our menu. The menu will be made up of as many sections as there are ITEMS. Any one of those ITEMS which has a URL will be made as a link button, while the other ITEMS with SUBITEM nodes will be made as dropdown menus containing link buttons for each of those SUBITEMS with the appropriate display name and URL.

In this example, by far the easiest part is the XML itself. Its clear how this works and how it should interact with Flash to provide it the correct information. The hardest part is getting through the actual menu operation code. The difficulty here is the fact that is is completely dynamic and constructed completely within the onLoad event of the XML object, being created once the information has been successfully read into flash. As for the XML specifically, conceptiually I will lay that out in this post getting into further menu detail in a follwoing post (if/when I ever feel so ambitious ;)).


Once the XML is loaded into the XML object, myXML, it needs to be read and understood correctly to generate the menu. So what do we need to know how to make a menu? Well off the top of my head Im thinking:

How many menu items there will be
The names of each menu item
What that menu item will do (link or open submenu)
- if a submenu opening item, how many submenus to attach

All this information is contained within the XML file. All we need to do then is extract it.

myXML.firstChild is <MENU>. myXML.firstChild.childNodes is the array containing the ITEM nodes. With that array we can easily get our number of items just by checking its length

myXML.firstChild.childNodes.length

Great! now we have our menu items! All we would need to do then in Flash is loop through that many number of times and attach a button for each menu item. Fairly easy. Now, within that loop, every time you attach a button you'll need to assign to it its name and its url (if it has one) and we get that through the attributes of that item. For example, you can see this using the following loop:

for (i=0; i< myXML.firstChild.childNodes.length; i++){
menu_mc.attachMovieClip("menuitemID","menuItem_mc"+i, i);
menu_mc.name_txt.text = myXML.firstChild.childNodes[i].attributes.NAME;
menu_mc.url = myXML.firstChild.childNodes[i].attributes.URL;
}

This loop goes through for each ITEM in the <MENU> node of the XML and attaches a movieclip and then assigns to theat moveiclip the NAME (input to a textField) and URL (just as a variable).

But what if the ITEM isnt a link item? Well then, wed first check for childNodes of that ITEM node. If they exist, then we wouldnt go through and give that menu item a URL, but rather give it a command to open the submenu - which itself Does exactly what is above, but just for the submenu. So the process is:


Loop through all ITEM nodes
If ITEM has no child nodes, assign it its own NAME and URL
If ITEM has children, give it its NAME and assign it an action to oepn a submenu and not a link
In creating a submenu (which is actually created at the time the sub menu item is clicked) perform the same process used to create your non submenu ITEMs to give the submenu ITEM names and functionality


The details of making that happen, especially in the manner of the example can get a little overwhelming, as seen in the code. Understanding atleast how the XML fits in, doesnt have to be.

lostinbeta
02-01-2003, 12:15 PM
I get it..... you have been a great help for me in learning XML in Flash Sen. It doesn't as difficult as people make it out to be.


Unless it gets more difficult depending on what your doing. I am up for any challenege in it though ;)

mindfriction
06-09-2003, 07:57 AM
Hi Lost/ Se, yerr I know this is an old thread, but I was going through the AS of the latest version of the xml menu and I was having a little trouble understanding the logic of the menu creation. Could someone plz summarise the logic ? Ie the AS and the function calls.

Thanks:P

senocular
06-10-2003, 11:06 AM
heh, anything specifically? It can get a little involved (which is why I havent gotten around to explaining it all) ;)

mindfriction
06-10-2003, 10:56 PM
LOL, yes it looks quiet involved thats for sure!. I even noticed the use of '?' in some of the condtionals which I know is deffintly a 'advanced shortcut' for people like you :P. Hmm well, i'll go through it again and see which parts I understand least and go from there...be back with my reply soon.

Actually Se eventually I want to be able to construct something like this
http://www.flashcomponents.net/component.cfm?nav=2&id=240
by myself (very nice isnt it?)

senocular
06-11-2003, 10:43 AM
ah well there ya go, all packaged in a pretty component, you dont need to re-write it yourself ;)

mindfriction
06-12-2003, 12:10 AM
LOL, yes it is pretty....But Im not a huge fan of components. They muck with preloaders and its somebody else's blodd sweat and tears :P. ..I would rather the satisfaction of my own work, and the learning process on the way. :smirk: Wouldnt you?

-As for getting back to you on which parts of the menu I dont understand Im to full with Univeristy study, as I have exams on atm :(

Ozeona
07-19-2005, 12:23 AM
hi

is anyone reviewing this thread?

anyway, i was working on flash using data from xml when i was stuck at a particular area.

The user should be able to click on the listbox (pulled from xml) to display whatever content it has specify(also from XML).

however i cannot get that part working. It only display the default content, and does not change to other content.

please help me?

codes for flash
myXML = new XML();
myXML.ignoreWhite = true;
myXML.sendAndLoad("../XMLs/features.xml", myXML);
status_txt.text = "Loading XML";
myXML.onLoad = function(success) {
if (success) {
status_txt.text = "Parsing XML";
setupContentList(this.firstChild);
} else {
status_txt.text = "Error Loading XML";
}
}
function setupContentList(inputXml) {
software = myXML.firstChild.firstChild;

do {
softwareList.addItem(software.attributes["name"]);
} while (software = software.nextSibling)

status_txt.text = "Ready.";

showContent();
softwareList.setChangeHandler("showContent");
resetFields();
drillDown(software);
trace(drillDown(xmlNode));
}
function showContent() {
contentName = softwareList.getSelectedItem().label;
rootNode = myXML.firstChild.firstChild;
software = rootNode.firstChild.firstChild;
do {
if (contentName == software.attributes["name"]) {
scrollable.fcontent.htmlText += rootNode;
break;
}
} while (rootNode = rootNode.nextSibling);
//trace(rootNode.nextSibling);
};
resetFields = function() {
contentInfo.text = "";

};
function drillDown(xmlNode) {
var xmlNode = myXML.firstChild.firstChild;
contentName = softwareList.getSelectedItem().label;
do {
contentName = xmlNode.attributes["id"]
switch (xmlNode.nodeName) {
case "contentInfo":
if (att == "info") {
scrollable.fcontent.htmlText = xmlNode;
}
break;
}
} while (xmlNode = xmlNode.nextSibling)
}




code for XML

<feature>
<software name = "Junior Publisher">
<contentInfo id ="info"><font face="Arial">
content</font>
</contentInfo>
</software>

<software name="Junior Musician">
<contentInfo id ="info">
more content
</contentInfo>
</software>
</feature>

ajit007
05-29-2007, 06:52 AM
thnxssssssssssss