The major limitation when using the BuilderSupport is it doesn't support the multiple namespaces which is very common.
E.g. I want to create the XML message to invoke Google calendar
<entry xmlns='http://www.w3.org/2005/Atom' xmlns:gCal='http://schemas.google.com/gCal/2005'>
<content type="html">Tennis with John April 11 3pm-3:30pm</content>
<gCal:quickadd value="true"/>
</entry>
I cannot build the message with current NamespaceBuilderSupport for there is only one namespace could be specified.
So, I create one NamespaceBuilderSupport then I can create the message in Groovy.
def builder = new NamespaceBuilderSupport (DOMBuilder.newInstance());
builder.namespace('http://www.w3.org/2005/Atom');
builder.namespace('http://schemas.google.com/gCal/2005', 'gCal')
def data = builder.entry {
"gCal:quickadd"(value:"true")
title("Tennis with John")
content(type:'html', "Tennis with wen Bing in PKU on February 5 3pm-3:30pm")
}
And the reference impl is as following.
public class NamespaceBuilderSupport extends BuilderSupport{
private Map<String, String> nsMap = new HashMap<String, String>();
public NamespaceBuilderSupport(BuilderSupport builder) {
super(builder);
}
protected NamespaceBuilderSupport namespace(String namespaceURI) {
nsMap.put("", namespaceURI);
return this;
}
protected NamespaceBuilderSupport namespace(String namespaceURI, String prefix) {
nsMap.put(prefix, namespaceURI);
return this;
}
protected Object getName(String methodName)
{
String prefix = "";
String localPart = methodName;
int idx = methodName.indexOf(':');
if (idx > 0 ) {
prefix = methodName.substring(0, idx);
localPart = methodName.substring(idx + 1);
}
String namespaceURI = nsMap.get(prefix);
if (namespaceURI == null) {
namespaceURI = "";
prefix = "";
}
return new QName(namespaceURI, localPart, prefix);
}
@Override
protected Object createNode(Object name) {
return name;
}
@Override
protected Object createNode(Object name, Object obj1) { return name; } }
@Override
protected Object createNode(Object name, Map map) {
return name;
}
@Override
protected Object createNode(Object name, Map map, Object obj1) { return name; } }
@Override
protected void setParent(Object obj, Object obj1) {
}
}
Thanks in advance. I hope it could be helpful.