[英]JAXB @XmlValue Not Working
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>
請注意, “內容”元素中沒有內容文本,顯示為“這是示例內容”。 但是,如果我在“ Content”元素內傳遞了其他元素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>
有什么想法為什么呢?
這已經解決了。 剛剛注意到,這與我的其他帖子重復,對不起。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.