XML DSL for Java 1.5
Lately I've been playing around with embedded DSLs for Java. Regular readers might remember my little LINQ experiment from a while back. Java 1.5s support for static import is a great way to "extend" the Java language with new expressions, and I'll be submitting an abstract to the JavaZone conference this year on leveraging various Java 1.5 / 1.6 features and design patterns to define embedded DSLs within Java.
One of the features coming up in Java 1.7 (codename Dolphin) is language level XML-support. This will enable you to declare an XML DOM like this:
org.w3c.dom.Document doc =
<employees>
<employee>
<name>Arthur Dent</name>
</employee>
</employee>;
Those who are familiar with the next version of Visual Basic will find this syntax familiar. Even if some people within the Java-community believe that DSLs like this don't add any real value and just make Java more 4GL-ish, I like the concept. One of my experiments was to bring a similar DSL to Java 1.5. Below you can see an example of how you can create a DOM document using an embedded Java 1.5 DSL.
Document doc=
document(
element("Employees",
element("Employee",
comment("Highly valued employee..."),
element("Id",42),
element("Name","Arthur Dent"),
element("ContactInfo",
element("Phonenumber","555-5555"),
element("Address","Upda Road 42"),
element("Country","England")
)
),
element("Employee",
attribute("toBeFired",true),
element("Id",3.14),
element("Name","Lay C. Slobb")
)
)
);
This code produces the following XML output:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Employees>
<Employee>
<!--Highly valued employee...-->
<Id>42</Id>
<Name>Arthur Dent</Name>
<ContactInfo>
<Phonenumber>555-5555</Phonenumber>
<Address>Upda Road 42</Address>
<Country>England</Country>
</ContactInfo>
</Employee>
<Employee toBeFired="true">
<Id>3.14</Id>
<Name>Lay C. Slobb</Name>
</Employee>
</Employees>
The DSL isn't as compact or self-explaining as Dolphin's XML support, but I think it is a much more readable than code that uses JDOM directly. Val has a good example of how cumbersome the DOM APIs actually are here.
I'm sorry for only showing off the client code for this, and I promise that I'll post the actual APIs that enable you to write Java code in this way as soon as I've sorted some minor bugs and cleaned up the code. Stay tuned!