您可以将文本包装在里面<![CDATA...]]>
:
<instructions size='1'>
<instruction key='manifest'>
<![CDATA[
Bundle-SymbolicName: org.slf4j.api&#xA;Bundle-Version: 1.6.4.v20120130-2120
]]>
</instruction>
</instructions>
我正在使用以下代码对其进行测试:
def out = new StringWriter()
def xml = new XmlParser().parseText(new File("file.xml").text)
def printer = new XmlNodePrinter(new PrintWriter(out))
printer.print(xml)
println out.toString()
输出如预期:
<instructions size="1">
<instruction key="manifest">
Bundle-SymbolicName: org.slf4j.api&#xA;Bundle-Version: 1.6.4.v20120130-2120
</instruction>
</instructions>
回复评论:
如果您真的别无选择,那么您可以扩展XmlNodePrinter
(这是一个 Java 类)并创建 Groovy 代码,例如:
class MyXmlNodePrinter extends XmlNodePrinter {
MyXmlNodePrinter(PrintWriter out) {
super(out)
}
void printSimpleItem(Object value) {
value = value.replaceAll("\n", "
")
out.print(value)
}
}
def out = new StringWriter()
def xml = new XmlParser().parseText(new File("file.xml").text)
def printer = new MyXmlNodePrinter(new PrintWriter(out))
printer.print(xml)
println out.toString()
这段代码的输出是:
<instructions size="1">
<instruction key="manifest">
Bundle-SymbolicName: org.slf4j.api
Bundle-Version: 1.6.4.v20120130-2120
</instruction>
</instructions>
这MyXmlNodePrinter
是微不足道的并且不会执行转义,因此您可能需要private void printEscaped(String s, boolean isAttributeValue)
从XmlNodePrinter
. XmlNodePrinter
您可以在https://github.com/groovy/groovy-core/blob/master/subprojects/groovy-xml/src/main/java/groovy/util/XmlNodePrinter.java中找到源代码