Showing posts with label xml namespace. Show all posts
Showing posts with label xml namespace. Show all posts

Saturday, January 12, 2013

Using XStream to set xmlns attribute (xml namespace)

Thoughtworks xstream does not have an API to add xmlns attribute to xml root element. There is a work around to do the same using their useAttributeFor() API. Its a bit of hack but serves the purpose.

java pojo
public class TestXmlns {
    private String name;
    private String address;
    private String xmlns;
   
    ...get/set for above attributes.
   
}

create an instance of xstream and add below configuration
xstream.useAttributeFor(TestXmlns.class, "xmlns");

Example:
TestXmlns x1 = new TestXmlns();
x1.setName("abc");
x1.setAddress("zyx");
z1.setXmlns("http://com.company.mytest");

XStream xstream = new XStream();
xstream.useAttributeFor(TestXmlns.class, "xmlns");

String xmlString = xstream.toXML(x1);

output
<TestXmlns xmlns="http://com.company.mytest">
    <name>abc</name>
    <address>xyz</address>
</TestXmlns>