开发者

Groovy pretty print XmlSlurper output from HTML?

I am using several different versions to do this but all seem to result in this error:

[Fatal Error] :1:171: The prefix "xmlns" cannot be bound to any namespace explicitly; neither can the namespace for "xmlns" be bound to any prefix explicitly.

I load html as:

// Load html file
def fis=new FileInputStream("2.html")
def html=new XmlSlurper(new  org.cyberneko.html.parsers.SAXParser()).parseText(fis.text)        

Versions I've tried:

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

import groovy.xml.StreamingMarkupBuilder
import groovy.xml.XmlUti开发者_如何学编程l
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()))
}

Any advice?

Thank you! Misha


The problem is namespaces. Here is the solution:

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

Thank you! Misha


Still don't have an answer but if I use XmlParser then

def html=new XmlSlurper(new org.cyberneko.html.parsers.SAXParser()).parseText(somehtml)        
new XmlNodePrinter(preserveWhitespace:true).print(html)

Will pretty print.

Also if you get a StreamingMarkupBuilder, you can do:

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

Misha

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜