How do I map the inner text content of an element

2019-05-26 13:55发布

问题:

Say I have the following XML and Java code respectively:

<foo>
My text content
</foo>
@XmlRootElement( name="foo" )
public static class Foo
{
  // This is where I want to see "My text content" stored
  private String text;

  // getters and setters
}

When I tried marshalling the XML, my Foo instance doesn't get its text property populated with value from the inner text of my foo element in the given XML. How do I solve this?

回答1:

You can use the @XmlValue annotation.

@XmlValue 
public String getText() {
    return text;
}

For More Information

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