How to create inner children without creating another class?

I need to create an XML like this:

<Root>
   <Children>
      <InnerChildren>SomethingM</InnerChildren>
   </Children>
</Root>

The simplest solution is to create an inner class in the Root class:

@Root
class Root{
    @Element
    Children element;

    @Root
    private static class Children{
        @Element
        String innerChildren;
    }
}

But I want to avoid creating an inner class, as this will look strange when using objects Root. Anyway, can I achieve this result without using inner classes?

The expected way to create Root objects:

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 awful
+3
source share
1 answer

Just use a regular class instead of an inner class. It should work:

@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 annotation Pathby specifying an XPath expression for the field innerChildren. For instance:

@org.simpleframework.xml.Root
class Root {
   @Element
   @Path("children")
   private final String innerChildren;

   public Root(String name){
       innerChildren = name;
   }
}

:

<root>
   <children>
      <innerChildren>Something</innerChildren>
   </children>
</root>

Namespace, . :

@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;
   }
}

:

<bla:root xmlns:bla="http://domain/parent">
   <bla:children>
      <bla:innerChildren>Something</bla:innerChildren>
   </bla:children>
</bla:root>

XML , : Element. :

<bla:root xmlns:bla="http://domain/parent">
   <blachildren>
      <bla:innerChildren>Something</bla:innerChildren>
   </blachildren>
</bla:root>

, :

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);
    }
}

:

<bla:root xmlns:bla="http://domain/parent">
   <bla:children>
      <bla:innerChildren>Something</bla:innerChildren>
   </bla:children>
</bla:root>
+7

Source: https://habr.com/ru/post/1785940/


All Articles