Java – how to create an internal child without creating another class?
I need to generate such XML:
<Root> <Children> <InnerChildren>SomethingM</InnerChildren> </Children> </Root>
The simplest solution is to create an internal class on the root class:
@Root class Root{ @Element Children element; @Root private static class Children{ @Element String innerChildren; } }
But I want to avoid inner class creation because it makes things look strange when using root objects Anyway, can I implement this result without using inner classes?
Expected method to create root object:
Root root = new Root("Something");
What I want to avoid:
Children child = new Children("Something"); Root root = new Root(child); // this Could be achieve by injecting some annotations // in the constructor,but it's awful
Solution
Just use ordinary classes instead of inner classes It should still be valid:
@org.simpleframework.xml.Root public class Root{ @Element Children children; public Root(){ children = new Children("Something"); } } @org.simpleframework.xml.Root public class Children{ @Element String innerChildren; public Children(String inner){ innerChildren = inner; } }
Update: if you do not want to create another class, you can use the path annotation by specifying an XPath expression for the innerchildren field For example:
@org.simpleframework.xml.Root class Root { @Element @Path("children") private final String innerChildren; public Root(String name){ innerChildren = name; } }
Production:
<root> <children> <innerChildren>Something</innerChildren> </children> </root>
Add a namespace using the namespace annotation For example:
@org.simpleframework.xml.Root @Namespace(reference="http://domain/parent",prefix="bla") class Root { @Element @Path("bla:children") @Namespace(reference="http://domain/parent",prefix="bla") private final String innerChildren; public Root(String name){ innerChildren = name; } }
Production:
<bla:root xmlns:bla="http://domain/parent"> <bla:children> <bla:innerChildren>Something</bla:innerChildren> </bla:children> </bla:root>
If you use styles to format XML, you need to make some changes because they are removed from the element: the result of using styles is:
<bla:root xmlns:bla="http://domain/parent"> <blachildren> <bla:innerChildren>Something</bla:innerChildren> </blachildren> </bla:root>
This is what I do:
public class MyStyle extends CamelCaseStyle{ @Override public String getElement(String name) { if( name == null ){ return null; } int index = name.indexOf(':'); if( index != -1 ){ String theRest = super.getElement(name.substring(index+1)); return name.substring(0,index+1)+theRest; } return super.getElement(name); } }
Now the result is the expected result:
<bla:Root xmlns:bla="http://domain/parent"> <bla:Children> <bla:InnerChildren>Something</bla:InnerChildren> </bla:Children> </bla:Root>