jaxb: inline elements

2019-02-26 09:00发布

问题:

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>

回答1:

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

  • http://blog.bdoughan.com/2011/06/jaxb-and-complex-types-with-simple.html


回答2:

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.



回答3:

I'm not sure you can to eliminate the tag bar from resulting XML:

http://docs.oracle.com/cd/E17802_01/webservices/webservices/docs/2.0/tutorial/doc/JAXBUsing4.html#wp148576



标签: java xml jaxb