如何在不创建另一个类的情况下创建内部孩子?
我需要生成这样的 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
I need to generate an XML like this:
<Root>
<Children>
<InnerChildren>SomethingM</InnerChildren>
</Children>
</Root>
The simplest solution is creating an inner class on the Root class:
@Root
class Root{
@Element
Children element;
@Root
private static class Children{
@Element
String innerChildren;
}
}
But I want to avoid that inner class creation, since it will make things look strange while using Root
objects. Is there anyway I can achieve that result without using inner classes?
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's awful
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需使用普通类而不是内部类即可。它应该仍然有效:
更新:
如果您不想创建另一个类,可以使用
Path
注释,通过为innerChildren
字段指定 XPath 表达式来实现。例如:生成:
使用
命名空间
注释来添加名称空间。例如:Produces:
如果使用样式来格式化 XML,则需要进行一些修改,因为它们从
Element
中删除了:
。使用样式的结果是:这就是我所做的:
现在的结果是预期的:
Just use a normal class instead of an inner class. It should still work:
Update:
If you do not want to create another class, you can use the
Path
annotation by specifying an XPath expression for theinnerChildren
field. For example:Produces:
Use the
Namespace
annotation to add name spaces. For example:Produces:
If using Styles to format the XML, it's necessary to do some modifications since they remove the
:
from theElement
. The result using styles is:This is what I did:
And now the result is the expected one: