3

我需要生成这样的 XML:

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

最简单的解决方案是在 Root 类上创建一个内部类:

@Root
class Root{
    @Element
    Children element;

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

但我想避免创建内部类,因为它会使使用Root对象时看起来很奇怪。无论如何我可以在不使用内部类的情况下实现这个结果吗?

创建 Root 对象的预期方法:

Root root = new Root("Something");

我想避免的:

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
4

1 回答 1

7

只需使用普通类而不是内部类。它应该仍然有效:

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

更新:如果您不想创建另一个类,可以通过为字段Path指定 XPath 表达式来使用注释。innerChildren例如:

@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>
于 2011-01-17T16:26:54.477 回答