[英]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; [致命错误]:1:171:前缀“xmlns”无法明确绑定到任何名称空间; neither can the namespace for "xmlns" be bound to any prefix explicitly.
“xmlns”的命名空间也不能明确地绑定到任何前缀。
I load html as: 我加载html为:
// 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 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 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 仍然没有答案,但如果我使用XmlParser
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: 此外,如果您获得StreamingMarkupBuilder,您可以:
import groovy.xml.XmlUtil
println XmlUtil.serialize(new StreamingMarkupBuilder().bind {
... make your markup here ...
}
)
Misha 米莎
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.