Groovy和XML:无法插入处理指令 [英] Groovy and XML: Not able to insert processing instruction
问题描述
需要更新现有XML文件中的某些属性。该文件包含XSL处理指令,因此,在解析和更新XML时,我需要在将指令再次写入文件之前添加该指令。问题是 - 无论我做什么 - 我无法插入处理指令
Need to update some attributes in an existing XML-file. The file contains a XSL processing instruction, so when the XML is parsed and updated I need to add the instruction before writing it to a file again. Problem is - whatever I do - I'm not able to insert the processing instruction
根据在rgagnon.com上找到的Java示例我已经创建了下面的代码
Based on the Java-example found at rgagnon.com I have created the code below
import groovy.xml.*
def xml = '''|<something>
| <Settings>
| </Settings>
|</something>'''.stripMargin()
def document = DOMBuilder.parse( new StringReader( xml ) )
def pi = document.createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="Bp8DefaultView.xsl"');
document.insertBefore(pi, document.documentElement)
println document.documentElement
创建输出
<?xml version="1.0" encoding="UTF-8"?>
<something>
<Settings>
</Settings>
</something>
我要的是什么
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="Bp8DefaultView.xsl"?>
<something>
<Settings>
</Settings>
</something>
推荐答案
$ c> documentElement ,但是只传递元素到 println
。如果您打印整个文档
?
You're inserting the PI before the documentElement
, but then passing only the element to println
. Does it work if you print the whole document
?
,它会起作用如果不这样做,输出DOM的官方方法document是使用 LSSerializer
Failing that, the "official" way to output a DOM document is to use LSSerializer
def ser = document.implementation.createLSSerializer()
new File("output.xml").withOutputStream { o ->
def lso = document.implementation.createLSOutput()
lso.byteStream = o
ser.write(document, lso)
}
这篇关于Groovy和XML:无法插入处理指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!