java - 如何在 Spring Boot 应用程序中插入 XML Prolog 到 Rest XML 响应
问题描述
如何在 Spring Boot 应用程序中将 XML Prolog 插入到 Rest XML 响应。
我在spring boot rest api中使用jackson xml数据格式。
我当前的 rest-xml 响应是:
<Response>
<person id = "hello">
<name>xyz</name>
</person>
</Response>
虽然我想要:
<?xml version = "1.0" encoding = "UTF-8"?>
<Response>
<person id = "hello">
<name>xyz</name>
</person>
</Response>
解决方案
希望这会对某人有所帮助:有一个完整的解决方案,从 Sambit 那里得到答案,稍微调整一下并编写了以下实用程序类。请注意,convertPojoToXmlString() 返回一个 XML 字符串,然后可以将其发送回调用者:
package com.xml.util;
import java.io.IOException;
import java.io.StringWriter;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import com.ctc.wstx.api.WstxInputProperties;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
/**
* @author ekariyev
*
*/
public class XmlUtil {
private final static XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
static {
xmlOutputFactory.setProperty(WstxInputProperties.P_RETURN_NULL_FOR_DEFAULT_NAMESPACE, true);
}
/**
* @param object
* @return
* @throws XMLStreamException
* @throws IOException
* @throws FactoryConfigurationError
*/
public static String convertPojoToXmlString(final Object object) throws XMLStreamException, IOException {
final StringWriter stringWriter = new StringWriter();
try {
final XMLStreamWriter sw = xmlOutputFactory.createXMLStreamWriter(stringWriter);
final XmlMapper mapper = new XmlMapper();
sw.writeStartDocument();
mapper.writeValue(sw, object);
sw.writeEndDocument();
sw.flush();
} finally {
stringWriter.close();
}
return stringWriter.toString();
}
}
该解决方案适用于:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.9.5</version>
</dependency>