4

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

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

有什么建议吗?

谢谢!米莎

4

2 回答 2

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

谢谢!米莎

于 2010-06-14T19:25:02.500 回答
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 ...
}
) 

米莎

于 2010-06-14T04:36:00.820 回答