XmlSlurper / NekoHTML documento fragmento de análisis - No HTML o el cuerpo etiquetas querido

StackOverflow https://stackoverflow.com/questions/3024488

Pregunta

Hola a todos, Estoy tratando de analizar el código HTML siguiente fragmento, y me gustaría conseguir el mismo fragmento como salida (sin etiquetas HTML y cuerpo). es posible? Si es así, ¿cómo?

Gracias Misha

p.s. Estoy leyendo aquí: http://nekohtml.sourceforge.net/faq.html#fragments y creo que he añadido las opciones correctas a continuación. Sin embargo, la salida sigue siendo incorrecta: (

Gracias Misha

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)

Salida:

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

Solución

Llamada setFeature en el objeto analizador directamente, así:

@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)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top