1

请查看我下面的常规代码,该代码按预期工作-但想知道是否有更好的方法来获取祖先信息?

我的示例 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>
4

2 回答 2

1

给你,内联评论:

//Get all the collection of materials which has titles
def materials = new XmlSlurper().parseText(record).material.findAll { it.books.title.size() }
//Print each node
materials.each { println groovy.xml.XmlUtil.serialize(it) }​

输出:

<?xml version="1.0" encoding="UTF-8"?><material>
  <books>
    <title>Italy</title>
  </books>
</material>

<?xml version="1.0" encoding="UTF-8"?><material>
  <books>
    <title>Greece</title>
  </books>
</material>

您可以在线快速试用Demo

编辑:基于 OP 评论

def materials = new XmlSlurper().parseText(record).material.findAll { it.books.title.size() } 
​println new groovy.xml.StreamingMarkupBuilder().bind { 
   mkp.yield materials
}.toString()
于 2017-06-30T05:44:46.003 回答
1

如果你不潜水太深,你不需要得到祖先。如果您想要材料节点,请获取那些对他们的孩子有条件的节点,而不是先让孩子们再上去。您的整个代码可以浓缩为这一行:

System.out.println new StreamingMarkupBuilder().bind { out << new XmlSlurper().parseText(record).material.findAll { it.books.title.size() } }
于 2017-06-30T02:13:36.537 回答