20
OCT

E4X - ECMAScript for XML

E4X is  an ECMA standard for handling XML natively in JavaScript (ECMA-357).    It's a nice extension to JavaScript, making XML a first-class citizen in the language. 

For example, it allows you to create an XML document directly in your code, like this :

var sales = <sales vendor="John">
                <name>John Smith</name>
                <other>
                    <code>A</code>
                </other>
                <item price="4" quantity="6" type="peas" />
                <item price="3" quantity="10" type="carrot" />
            </sales>;

and then work with it directly as an object :

print( sales.@vendor );
print( sales.item.( @price < 5 ).quantity );

 

Or, you can get an XML document from elsewhere and digest it into a nice object to work with.  For example, here's a RSS reader.  Just take this code and put in a .jxp file.  Run in our SDK :

<%
var feed = new XML( download( "http://www.10gen.com/blog/rss" <http://www.10gen.com/blog/rss> ).asString() );
feed = feed.channel;
%>
<h1><a href="<%= feed.link %>"><%= feed.title %></a></h1>
<p><%= feed.description %></p>
<%
for each( item in feed.item ) {
    %>
    <div class="item">
      <h3><a href="<%= item.link %>"><%= item.title %></a></h3>
      <p>By <%= item.author %></p>
      <p><%= item.pubDate %></p>
      <div class="desc">
        <%= item.description %>
      </div>
    </div>
    <%
}
%>

Have fun.  Let us know of any compliments, concerns or complaints.

| Back to main page

Categories: appserver javascript sdk

add a comment