Groovy pretty print XmlSlurper从HTML输出?

Groovy pretty print XmlSlurper从HTML输出?,html,groovy,xmlslurper,Html,Groovy,Xmlslurper,我使用了几种不同的版本来执行此操作,但似乎都会导致此错误: [致命错误]:1:171:前缀“xmlns”不能显式绑定到任何命名空间;“xmlns”的命名空间也不能显式绑定到任何前缀 我将html加载为: // Load html file def fis=new FileInputStream("2.html") def html=new XmlSlurper(new org.cyberneko.html.parsers.SAXParser()).parseText(fis.text)

我使用了几种不同的版本来执行此操作,但似乎都会导致此错误:

[致命错误]:1:171:前缀“xmlns”不能显式绑定到任何命名空间;“xmlns”的命名空间也不能显式绑定到任何前缀

我将html加载为:

// Load html file
def fis=new FileInputStream("2.html")
def html=new XmlSlurper(new  org.cyberneko.html.parsers.SAXParser()).parseText(fis.text)        
我尝试过的版本:

//输出
导入groovy.xml.MarkupBuilder
导入groovy.xml.StreamingMarkupBuilder
导入groovy.util.XmlNodePrinter
导入groovy.util.slurpersupport.NodeChild
def打印节点(NodeChild节点){
def writer=new StringWriter()

writer仍然没有答案,但是如果我使用XmlParser

def html=new XmlSlurper(new org.cyberneko.html.parsers.SAXParser()).parseText(somehtml)        
new XmlNodePrinter(preserveWhitespace:true).print(html)
会很漂亮的

此外,如果您获得StreamingMarkupBuilder,您可以执行以下操作:

import groovy.xml.XmlUtil
println XmlUtil.serialize(new StreamingMarkupBuilder().bind {
    ... make your markup here ...
}
) 

Misha

问题在于名称空间。以下是解决方案:

def saxParser=new org.cyberneko.html.parsers.SAXParser()
saxParser.setFeature('http://xml.org/sax/features/namespaces',false)
new XmlSlurper(saxParser).parseText(text)    

import groovy.xml.XmlUtil
println XmlUtil.serialize(new StreamingMarkupBuilder().bind {
                mkp.yield page
              })
谢谢大家!!
Misha

不确定这是否是可接受的答案。
XmlUtil.serialize
在内部将
StreamingMarkupBuilder.bind
返回的
可写的
转换为字符串。这会破坏整个流式处理过程。
import groovy.xml.XmlUtil
println XmlUtil.serialize(new StreamingMarkupBuilder().bind {
    ... make your markup here ...
}
) 
def saxParser=new org.cyberneko.html.parsers.SAXParser()
saxParser.setFeature('http://xml.org/sax/features/namespaces',false)
new XmlSlurper(saxParser).parseText(text)    

import groovy.xml.XmlUtil
println XmlUtil.serialize(new StreamingMarkupBuilder().bind {
                mkp.yield page
              })