Showing posts with label E4X. Show all posts
Showing posts with label E4X. Show all posts

Saturday, October 11, 2008

XML operation using javascript E4X from Rhino javascript shell

Firstly, download Rhino and install it. Here is a tutorial.
Then, run below command line:

$> java org.mozilla.javascript.tools.shell.Main
Rhino 1.7 release 1 2008 03 06
js> var user = <user id="1"><name type="firstname">Yu</name><name type="lastname">test</name><country>zh_CN</country></user>;
js> user
<user id="1">
<name type="firstname">Yu</name>
<name type="lastname">test</name>
<country>zh_CN</country>
</user>
js> typeof a
undefined
js> typeof user
xml
js> user.name
<name type="firstname">Yu</name>
<name type="lastname">test</name>
js> user.country
zh_CN
js> user.id

js> user.@id
1
js> user.@id = 100
100
js> user
<user id="100">
<name type="firstname">Yu</name>
<name type="lastname">test</name>
<country>zh_CN</country>
</user>
js> user.name[0]
Yu
js> user.name += <name type="nickname">_test</name>;
<name type="firstname">Yu</name>
<name type="lastname">test</name>
<name type="nickname">_test</name>
js> user
<user id="100">
<name type="firstname">Yu</name>
<name type="lastname">test</name>
<name type="nickname">_test</name>
<country>zh_CN</country>
</user>
js> user.name[1]
test
js> user.name[1].@type
lastname
js> for each(var n in user.name) print("The " + n.@type + " name is " + n);
The firstname name is Yu
The lastname name is test
The nickname name is _test
js> for each(var n in user..name) print("The " + n.@type + " name is " + n);
The firstname name is Yu
The lastname name is test
The nickname name is _test
js> quit();

The user..name selector just like the "//" operator in XPath.
$> cat echo.js
for (i in arguments) {
print(arguments[i])
}

$> java org.mozilla.javascript.tools.shell.Main echo.js test yu from google
test
yu
from
google

Reference:
http://developer.mozilla.org/en/Rhino_Shell

Test javascript e4x in firefox3

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test javascript e4x</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>

也可以将script的type直接写成"text/javascript"<br/>
<script type="text/javascript;e4x=1">

var person = <description>
<name>_test</name>
<sex>male</sex>
<age>30</age>
</description>;

document.write("The person' name is '" + person.name + "'");

</script>

</body>
</html>