jaxb: inline elements

2019-02-26 08:59发布

Given:

@XmlRootElement(name = "foo")
class Foo {
   public Bar getBar() {...}
}

class Bar {
   @XmlElement(name = "string")
   public String getString() {return "hello";}
}

How do I annotate so the XML will be:

<foo>
   <string>hello</string>
</foo>

标签: java xml jaxb
3条回答
Ridiculous、
2楼-- · 2019-02-26 09:35

You probably need to use @XmlSeeAlso annotation on top of your class.

You can use @XmlSeeAlso annotation when you want another Entity bean to be included in the XML output. Can you try this in your Foo class

@XmlRootElement(name = "foo")
@XmlSeeAlso(Bar.class)
class Foo {
   public Bar getBar() {...}
}

Update1:

For your comment to remove the bar tag in the XML try using EclipseLink JAXB (MOXy)'s. @XmlPath will solve your issue.

@XmlRootElement(name = "foo")
@XmlSeeAlso(Bar.class)
class Foo {
   @XmlPath(".")
   public Bar getBar() {...}
}

Refer here for more details.

查看更多
ら.Afraid
3楼-- · 2019-02-26 09:49
Fickle 薄情
4楼-- · 2019-02-26 09:57

You could do the following leveraging the @XmlValue annotation.

Foo

@XmlRootElement
class Foo {
    @XmlElement(name="string")
    public Bar getBar() {...}
}

Bar

class Bar {
    @XmlValue
    public String getString() {return "hello";}
}

For More Information

查看更多
登录 后发表回答