我需要生成这样的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 = 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
答案 0 :(得分: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;
}
}
<强>更新强>:
如果您不想创建另一个类,可以通过为innerChildren
字段指定XPath表达式来使用Path
注释。例如:
@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>