XmlMapper未转义大于号,XML合规性及强制转义方法问询
Jackson XML序列化:未转义
>的规范问题与解决方法 问题背景
我用Jackson将POJO序列化为XML字符串时,发现生成的XML里&和<已被转义,但>字符未被转义。相关代码如下:
实体类代码
// 容器类ContainerClass public class ContainerClass{ @JacksonXmlProperty(localName = "ListOfItems") private List<Item> list; } // Item类 public class Item { private String value; private EnumOfItemTypes ItemType; // 枚举值带有@JsonProperty()注解 public Item() { // value字段示例文本 this.value = "<<some place holder>> that uses " + "reserved xml characters & is actually " + "what is causing the problem"; this.ItemType = EnumOfItemTypes.ITEM_100; // 修正枚举命名,符合Java语法规范 } }
序列化代码
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; public class Main { public static void main(String[] args) throws Exception { SomeClass rootObject = new SomeClass(); // 初始化rootObject,包含上述Container对象及对应值 XmlMapper xmlMapper = XmlMapper.builder().defaultUseWrapper(false).build(); String dataXML = xmlMapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootObject); System.out.println(dataXML); } }
问题1:XML中值里的>未转义是否符合技术规范?
符合规范。根据XML 1.0标准,字符数据中只有<和&是必须转义的;>属于可选转义的字符——只要它不是]]>序列的一部分(]]>是CDATA段的结束标记),单独出现的>不会导致XML解析错误,所有合规的XML解析器都能正确识别处理。
问题2:如何强制Jackson也转义>字符?
Jackson的XML序列化依赖Stax API,默认使用Woodstox作为Stax实现。要强制转义>,需要配置Woodstox的输出属性:
- 确保项目中引入Woodstox依赖(若未引入):
<!-- Maven依赖示例 --> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> <version>2.15.2</version> <!-- 使用对应版本 --> </dependency> <dependency> <groupId>org.codehaus.woodstox</groupId> <artifactId>woodstox-core-asl</artifactId> <version>4.4.1</version> </dependency>
- 配置XmlMapper时,指定自定义的Woodstox输出工厂,开启
>转义:
import com.ctc.wstx.api.WstxOutputProperties; import com.ctc.wstx.stax.WstxOutputFactory; import com.fasterxml.jackson.dataformat.xml.XmlMapper; public class Main { public static void main(String[] args) throws Exception { SomeClass rootObject = new SomeClass(); // 初始化rootObject // 配置Woodstox输出工厂,强制转义> WstxOutputFactory outputFactory = new WstxOutputFactory(); WstxOutputProperties outputProps = new WstxOutputProperties(); outputProps.setProperty(WstxOutputProperties.P_OUTPUT_ESCAPE_GT, true); outputFactory.setOutputProperties(outputProps); // 构建XmlMapper XmlMapper xmlMapper = XmlMapper.builder() .defaultUseWrapper(false) .outputFactory(outputFactory) .build(); String dataXML = xmlMapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootObject); System.out.println(dataXML); } }
配置完成后,Jackson序列化时会将值中的>转义为>。
内容的提问来源于stack exchange,提问作者Sirmyself
相关产品推荐
相关产品推荐

