简体   繁体   中英

Escaping Curly Braces in AS3's XML variable

I am trying to create a XML variable but I need to include a { and } in it.

public class MyClass {

    private var simple:XML = 
        <config>
            <url>{PROTOCOL}://{SERVER}/{FOLDER}/</url>
        </config>


    ...

}

Flex is trying to find a variable named PROTOCOL , SERVER and FOLDER . I need to prevent this by escaping the curly brackets.

Question: How can I escape curly braces?

I have a couple of thoughts:

  • You can place the entire thing in a String and then cast the String (see here for getting a multi-line String)
  • You can use replace the { with &#123; (replacing } with &#125; is optional) .
  • Add the node in afterwards (sucks, but technically it is an option)

I would assign the text to a string then bind that string inside the XML - avoids having to escape everything.

public class MyClass {

    private var simple:XML = null;

    public function MyClass()
    {
        super();

        var s:String = "{PROTOCOL}://{SERVER}/{FOLDER}/";
        simple = <config>
            <url>{s}</url>
        </config>;
    }

    ...

}

If you have to have a lot of text that requires escaping then you might need to look into creating the XML instance from a string as suggested by cwallenpoole or creating a function that will bind the string for a particular element and then appending it to the appropriate parent element.

I would expect if you use a CDATA declaration, this should compile w/o problems. That is the same way MXML allows "non-standard XML" inside a Script tag:

private var simple:XML = 
    <config>
        <url><![CDATA[{PROTOCOL}://{SERVER}/{FOLDER}/]]></url>
    </config>

There doesn't seem to be a standard HTML Entity code for the curly bracket; but based on @cwallenpoole answer, you could create it using the ASCII code . { for the open bracket and } for the close bracket:

private var simple:XML = 
    <config>
        <url>&#123;PROTOCOL&#125;://&#123;SERVER&#125;/&#123;FOLDER&#125;</url>
    </config>

You can also escape the {} w/ a backslash. For example, {} are used in regular expressions, but also denote binding when using RegExpValidator.

<mx:RegExpValidator id="regExpValidator"
                    expression="[A-Za-z0-9]\{2\}[0-9]\{1,4\}"
                    flags="gi"
                    required="true" />

This lets {2} flow through to the expression instead of evaluating to 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM