Marshaller生成的xml去掉报文头、设置格式、不处理转义字符的方法

try {
			JAXBContext context = JAXBContext.newInstance(Entity.class);
			Marshaller marshaller = context.createMarshaller();
			// xml格式
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			// 去掉生成xml的默认报文头
			marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
			// 不进行转义字符的处理
			marshaller.setProperty(CharacterEscapeHandler.class.getName(), new CharacterEscapeHandler() {
				public void escape(char[] ch, int start,int length, boolean isAttVal, Writer writer) throws IOException {
					writer.write(ch, start, length);
				}
			});
			StringWriter sw = new StringWriter();
			marshaller.marshal(entity, sw);
			return sw.toString();
		} catch (JAXBException e) {
			log.error("", e);
		}


其中,类CharacterEscapeHandler为com.sun.xml.internal.bind.marshaller.CharacterEscapeHandler

  • 4
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
在使用JAXB生成XML时,如果需要动态生成`xmlns:xsi`属性,可以使用`javax.xml.bind.Marshaller.JAXB_SCHEMA_LOCATION`属性来指定XML Schema的位置和命名空间,并通过`javax.xml.bind.Marshaller.setProperty()`方法将该属性设置为要生成XML中的`xmlns:xsi`属性的值。例如: ``` JAXBContext jaxbContext = JAXBContext.newInstance(Root.class); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://example.com/ns path/to/schema.xsd"); marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapper() { @Override public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) { if ("http://www.w3.org/2001/XMLSchema-instance".equals(namespaceUri)) { return "xsi"; } return null; } }); Root root = new Root(); marshaller.marshal(root, System.out); ``` 在这个例子中,`Marshaller.JAXB_SCHEMA_LOCATION`属性指定了XML Schema的位置和命名空间。`com.sun.xml.bind.namespacePrefixMapper`属性用于将`http://www.w3.org/2001/XMLSchema-instance`命名空间映射到`xsi`前缀。在生成XML时,JAXB会自动将`xmlns:xsi`属性添加到生成XML中,并将其值设置为`http://www.w3.org/2001/XMLSchema-instance`。例如: ``` <root xmlns="http://example.com/ns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://example.com/ns path/to/schema.xsd"> ... </root> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值