As3 CData Binding

March 4th, 2009

I just manged to get some code working that has had me banging my head against the wall for the last couple of hours.
The goal was simple, send XHTML markup to PHP. Horray says me, should be fairly straight forward!
I’ll just pop a <!CDATA[..]]>> tag around the nodes that store the markup so the tags will not be parsed.
Then i set off about my usual workflow, and soon enough, i have some actionscript which should be both reading and writing to my .xml file.

Everything looks great, time to test it out!

Problem!

1
2
3
4
5
6
7
8
9
10
// Wraps a single content node with required tags.
// Note tag = "Name" & contents = "Raz Peel"
function stringToNode (tag:String, contents:String):XML
{
    return new XML (
            <{tag}>
                +"<![CDATA["+{contents}+"]]>"+
            </{tag}>
        );
}

My first element comes out as such.

<Name>
+ "
<![CDATA[" + {contents} + "]]>
" +
</Name>

Obviously this is not working at all as it should, i take it my XML isn’t formatted correctly.
Back into code I rewrite my function to the follows:

1
2
3
4
5
return new XML (
            <{tag}>
                <![CDATA[ {contents} ]]>
            </{tag}
            );

This result was better, but still very much incorrect.

<Name><![CDATA[ {contents} ]]></Name>

The contents variable was being parsed as a string rather than a variable.
I jumped back into the code to try something else.

1
2
3
4
5
return new XML (
            <{tag}>
                {"<![CDATA["}{contents}{"]]>"}
            </{tag}>
            );

This must work right? Apparantly not, result was:

<Name>&lt;![CDATA[ Raz Peel ]]&gt;</Name>

This is the point where i consulted the Adobe LiveDocs
and then our Essential ActionScript 3.0 book.
Colin, unfortunatley, confirmed that i wasn’t doing anything wrong, weird! Ten minutes on google found me on Jesse Warden’s blog reading this post.
As such i changed my code to this:

1
2
3
4
5
6
7
8
function cdata(theURL:String):XML
{
    return new XML ("<![CDATA[" + theURL + "]]>");
}

return new XML (
            <{tag}>{cdata(contents)}</{tag}>
            );

Result?

<Name><![CDATA[Raz Peel]]></Name>

Yay, success!!!
I’ve no idea if this is suppose to work like this or not, but it does.
Thanks for sharing Jesse!

Twitter / RazPeel

Trackback URI | Comments RSS

Name (required)

Email (required)

Website


Speak Your Mind





Powered by WP Hashcash

About

Name: Raz Peel

Raz Peel 2009

Employer: Sapient
Occupation: Web Developer
Contact: raz@wizardelraz.com