请查看我下面的常规代码,该代码按预期工作-但想知道是否有更好的方法来获取祖先信息?
我的示例 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>
'''
我想知道是否有更好的方法来优化这一点获得祖先?
GPathResult extractedMaterialBlocks = extractAllMaterialBlocks(record)
String finalXml = serializeXml(extractedMaterialBlocks.parent().parent(), 'UTF-8')
println "finalXml : ${finalXml}"
我的方法:
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()
}
按预期输出:
<material>
<books>
<title>Italy</title>
</books>
</material>
<material>
<books>
<title>Greece</title>
</books>
</material>