如何在Java-XML中禁用/避免和符号转义? [英] How to disable/avoid Ampersand-Escaping in Java-XML?

查看:1759
本文介绍了如何在Java-XML中禁用/避免和符号转义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个空格替换为  的XML。但是,Java-Transformer会转出&符号,因此输出为& amp; amp;#160;

I want to create a XML where blanks are replaced by  . But the Java-Transformer escapes the Ampersand, so that the output is  

是我的示例代码:

public class Test {

    public static void main(String[] args) {

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.newDocument();

        Element element = document.createElement("element");
        element.setTextContent(" ");
        document.appendChild(element);

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        StreamResult streamResult = new StreamResult(stream);
        transformer.transform(new DOMSource(document), streamResult);
        System.out.println(stream.toString());

    }

}

这是我的示例代码的输出:

And this is the output of my sample code:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<element>&amp;#160;</element>

任何想法要修复或避免?非常感谢!

Any ideas to fix or avoid that? thanks a lot!

推荐答案

将文本内容直接设置为您想要的字符,如果需要,序列化程序会将其转义为您:

Set the text content directly to the character you want, and the serializer will escape it for you if necessary:

element.setTextContent("\u00A0");

这篇关于如何在Java-XML中禁用/避免和符号转义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆