Pregunta

Estoy usando XMlSlurper.Mi código está abajo (pero no funciona).El problema es que falla cuando golpea un nodo que no tiene el atributo "ID".¿Cómo explico esto?

//Parse XML
def page = new XmlSlurper(false,false).parseText(xml)

//Now save the value of the proper node to a property (this fails)
properties[ "finalValue" ] = page.find {
    it.attributes().find { it.key.equalsIgnoreCase( 'id' ) }.value == "myNode"
};

Solo debo tener en cuenta los nodos sin el atributo "ID", por lo que no falla.¿Cómo hago eso?

¿Fue útil?

Solución 2

Aprezmente puedo hacer que funcione cuando simplemente utilice PROTEPTHFIRST.Entonces:

properties[ "finalValue" ] = page.depthFirst().find {
    it.attributes().find { it.key.equalsIgnoreCase( 'id' ) }.value == "myNode"
};

Otros consejos

Alternativamente, podría usar la notación de gpath, y verificar si "@id" está vacío primero.

El siguiente fragmento de código encuentra el último elemento (ya que el atributo ID es "B" y el valor también es "Bizz", se imprime "Bizz" y "B").

def xml = new XmlSlurper().parseText("<foo><bar>bizz</bar><bar id='A'>bazz</bar><bar id='B'>bizz</bar></foo>")
def x =  xml.children().find{!it.@id.isEmpty() && it.text()=="bizz"}
println x
println x.@id

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top