2010-06-11 134 views
3

我正在使用几个不同的版本来做到这一点,但所有似乎都会导致此错误:Groovy漂亮打印XmlSlurper从HTML输出?

[致命错误]: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)   

版本我已经试过:

http://johnrellis.blogspot.com/2009/08/hmmm_04.html

import groovy.xml.StreamingMarkupBuilder 
import groovy.xml.XmlUtil 
def streamingMarkupBuilder=new StreamingMarkupBuilder() 
println XmlUtil.serialize(streamingMarkupBuilder.bind{mkp.yield html}) 

http://old.nabble.com/How-to-print-XmlSlurper%27s-NodeChild-with-indentation--td16857110.html

// Output 
import groovy.xml.MarkupBuilder 
import groovy.xml.StreamingMarkupBuilder 
import groovy.util.XmlNodePrinter 
import groovy.util.slurpersupport.NodeChild 

def printNode(NodeChild node) { 
    def writer = new StringWriter() 
    writer << new StreamingMarkupBuilder().bind { 
     mkp.declareNamespace('':node[0].namespaceURI()) 
     mkp.yield node 
    } 
    new XmlNodePrinter().print(new XmlParser().parseText(writer.toString())) 
} 

有什么建议?

谢谢! 米莎

回答

5

问题是命名空间。这里是解决方案:

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

+0

不知道这应该是被接受的答案。 'XmlUtil.serialize'内部将'StreamingMarkupBuilder.bind'返回的'Writable'转换为String。这打败了整个流式传输。 – Dave 2018-01-24 10:14:40

0

仍然没有一个答案,但如果我使用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 ... 
} 
) 

米莎