XmlSlurper / NekoHTML文档片段解析 - 不需要HTML或BODY标记

时间:2010-06-11 16:31:21

标签: groovy fragment xmlslurper cyberneko

亲爱的所有人,我正在尝试解析以下HTML片段,我想获得与输出相同的片段(没有HTML和BODY标签)。这可能吗?如果是这样,怎么样?

谢谢 米莎

P.S。我在这里读到: http://nekohtml.sourceforge.net/faq.html#fragments 我相信我在下面添加了正确的选项。但是,输出仍然不正确:(

谢谢 米莎

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


def text="""
<div><h2>Test</h2>
<div>Hi</div>
</div>
"""

// Parse
def config=new org.cyberneko.html.HTMLConfiguration()
config.setFeature("http://cyberneko.org/html/features/balance-tags/document-fragment",true)
def html=new XmlSlurper(new org.cyberneko.html.parsers.SAXParser()).parseText(text)          

// Output
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()))
}
printNode(html)

输出:

<HTML>
  <tag0:HEAD xmlns:tag0="http://www.w3.org/1999/xhtml"/>
  <BODY>
    <DIV>
      <H2>
        Test
      </H2>
      <DIV>
        Hi
      </DIV>
    </DIV>
  </BODY>
</HTML>

1 个答案:

答案 0 :(得分:2)

直接在解析器对象上调用setFeature,如下所示:

@Grab(group='net.sourceforge.nekohtml', module='nekohtml', version='1.9.14')

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


def text="""
<div><h2>Test</h2>
<div>Hi</div>
</div>
"""

// Parse
def parser=new org.cyberneko.html.parsers.SAXParser()
parser.setFeature("http://cyberneko.org/html/features/balance-tags/document-fragment",true)
def html=new XmlSlurper(parser).parseText(text)          

// Output
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()))
}
printNode(html)