JAXB @XmlValue不起作用

时间:2018-08-20 23:37:26

标签: spring-boot jaxb moxy jaxb2

SampleMessage类:

@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;
        }
    }
}

Spring Boot-Rest Controller我有一个follow方法,该方法基本上只输出与我们传递的相同的XML形式,应该是这样。这只是检查它是否正确解析了XML。

@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示例1 :这是我拥有的初始XML示例:

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

输出(XML示例1):我从编组器得到的输出是:

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

请注意,“内容” 元素中没有内容文本,显示为“这是示例内容”。但是,如果我在“内容”元素中传递了其他元素 Value ,则它可以正确输出。

XML示例2

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

正确的输出

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

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

此问题已解决。刚刚注意到,这是我其他帖子的重复内容,对不起。

JAXB @XmlValue not able to get the text, Not generating empty XML element, and not able to read attribute