首页 > 解决方案 > JAXB @XmlValue Not Working

问题描述

SampleMessage class:

@XmlRootElement(name = "SampleMessage")
@XmlAccessorType(XmlAccessType.FIELD)
public class SampleMessage {
    @XmlAttribute
    private String type;

    @XmlElement(name = "Content", required = true)
    private Content content;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Content getContent() {
        return content;
    }

    public void setContent(Content content) {
        this.content = content;
    }

    @XmlAccessorType(XmlAccessType.FIELD)
    private static class Content {
        @XmlValue
        private String value;

        @XmlAttribute(name = "name")
        private String name;

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}

The Spring Boot - Rest Controller I have the follow method which basically just output the same XML form with what we passed, well supposed to be. This is just to check if it is parsing the XML properly.

@PostMapping(consumes = {MediaType.TEXT_XML_VALUE, MediaType.APPLICATION_XML_VALUE})
public String handler(@RequestBody SampleMessage message) {
    StringWriter writer = new StringWriter();

    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(SampleMessage.class);

        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(message, writer);
    } catch (JAXBException ex) {
        System.out.println(ex.toString());
    }

    return writer.toString();
}

XML Sample 1: This is the initial XML sample I have:

<?xml version="1.0" encoding="UTF-8"?>
<SampleMessage type="TestType">
  <Content name="TestContent">This is a sample content.</Content>
</SampleMessage>

Output (XML Sample 1): The output I get from the marshaller is this:

<?xml version="1.0" encoding="UTF-8"?>
<SampleMessage type="TestType">
   <Content name="TestContent"/>
</SampleMessage>

Notice that there is no content text in the "Content" element that reads "This is a sample content". However, if I pass additional element Value inside "Content" element then it is able to output correctly.

XML Sample 2

<?xml version="1.0" encoding="UTF-8"?>
<SampleMessage type="TestType">
  <Content name="TestContent"><Value>This is a sample content.</Value></Content>
</SampleMessage>

Correct Output

<?xml version="1.0" encoding="UTF-8"?>
<SampleMessage type="TestType">
   <Content name="TestContent">This is a sample content.</Content>
</SampleMessage>

Any thoughts why is this?

标签: spring-bootjaxbmoxyjaxb2

解决方案


这已经解决了。刚刚注意到这是我其他帖子的重复,对不起。

JAXB @XmlValue 无法获取文本,无法生成空 XML 元素,也无法读取属性


推荐阅读