Groovy and XML: Not able to insert processing instruction

ぐ巨炮叔叔 提交于 2020-01-25 07:34:28

问题


Scenario

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

Based on the Java-example found at rgagnon.com I have created the code below

Example code ##

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

Creates output

<?xml version="1.0" encoding="UTF-8"?>
<something>
  <Settings>
  </Settings>
</something>

What I want

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="Bp8DefaultView.xsl"?>
<something>
  <Settings>
  </Settings>
</something>

回答1:


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?

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)
}


来源:https://stackoverflow.com/questions/13781637/groovy-and-xml-not-able-to-insert-processing-instruction

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!