代码之家  ›  专栏  ›  技术社区  ›  AracKnight

在groovy XMLslurper中过滤特定标记

  •  1
  • AracKnight  · 技术社区  · 7 年前

    我有一个xml文档,我想用XMLslurper解析它。这实际上工作得很好,但是我在读取一些标记时遇到了问题,因为在同一个节点中可能有多行这样的标记:

    <element name="ABC">
        <description>lorem ipsum</description>
        <description>foo</description>
        <description type="DETAILED">some text</description>
    </element>
    

    element.description.text() 现在,我明白了 lorem ipsumfoosome text 作为输出。我必须如何对其进行编码,以便:

    1. description 标签已读取
    2. description type="DETAILED" 标签已读取
    1 回复  |  直到 7 年前
        1
  •  3
  •   Szymon Stepniak    7 年前

    XmlSlurper 您访问 element 标记为 NodeChildren 哪个实现了 Iterable 接口。这就是为什么可以应用以下操作:

    1. Iterable.first() ) :

      element.description.first()?.text()
      
    2. 获取类型为的第一个描述标记 DETAILED ( Collection.find(Closure cl) ):

      element.description.find { it.@type == 'DETAILED' }?.text()
      
    3. Iterable.join(String separator) ):

      element.description.join(' ')
      

    完整示例:

    def xml = '''
    <element name="ABC">
        <description>lorem ipsum</description>
        <description>foo</description>
        <description type="DETAILED">some text</description>
    </element>
    '''
    
    def element = new XmlSlurper().parseText(xml)
    
    println element.description.first()?.text()
    println element.description.find { it.@type == 'DETAILED' }?.text()
    println element.description.join(' ')
    

    lorem ipsum
    some text
    lorem ipsum foo some text