0

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

谢谢米莎

ps 我在这里阅读: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>
4

1 回答 1

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)
于 2010-06-11T17:46:57.497 回答