S'il vous plaît voir mon code ci-dessous groovy qui fonctionne comme prévu - mais se demandait s'il y a une meilleure façon d'obtenir des informations ancêtres?Existe-t-il un meilleur moyen de trouver des ancêtres dans XML en utilisant Groovy Gpath?
Mon échantillon record xml:
String record = '''
<collections>
<material>
<books>
<title>Italy</title>
</books>
</material>
<material>
<books>
<title>Greece</title>
</books>
</material>
<material>
<books>
<author>Germany</author>
</books>
</material>
<material>
<cd>
<author>France</author>
</cd>
</material>
</collections>
'''
Je me demande s'il y a une meilleure façon d'optimiser ce bit d'obtenir les ancêtres?
GPathResult extractedMaterialBlocks = extractAllMaterialBlocks(record)
String finalXml = serializeXml(extractedMaterialBlocks.parent().parent(), 'UTF-8')
println "finalXml : ${finalXml}"
Mes méthodes:
GPathResult extractAllMaterialBlocks(String record) {
GPathResult result = new XmlSlurper().parseText(record)
return result ? result.'material'?.'books'?.'title'?.findAll { it } : null
}
String serializeXml(GPathResult xmlToSerialize, String encoding) {
def builder = new StreamingMarkupBuilder()
builder.encoding = encoding
builder.useDoubleQuotes = true
return builder.bind {
out << xmlToSerialize
}.toString()
}
sortie comme prévu:
<material>
<books>
<title>Italy</title>
</books>
</material>
<material>
<books>
<title>Greece</title>
</books>
</material>
Voulez-vous séparer chaque élément 'material'? ce que vous avez montré n'est pas bien formé, n'est-ce pas? – Rao
Oui, vous avez raison, la sortie ci-dessus n'est pas bien formée, mais j'avais besoin que ce bloc de nœud actuel soit ajouté à un autre arbre de document bien formé. – user292049