Groovy:如何在使用 XMLSlurper() 读取的 XML 元素列表的开头插入节点

2024-03-15

我可能错过了一些明显的东西,因为我是 Groovy 的菜鸟,但我已经搜索过,但还没有找到我想要的东西。我有一个测试类,我正在其中读取一些 XML;我想插入一个元素一开始一系列的元素。我已经弄清楚如何replace第一个元素,我已经弄清楚如何append一个节点到列表的末尾,但我似乎无法理解如何在列表的开头(或者理想情况下,任何任意位置)插入一个元素。

例如:

@Test
void foo()
{
    def xml = """<container>
                   <listofthings>
                       <thing id="100" name="foo"/>
                   </listofthings>
                 </container>"""

    def root = new XmlSlurper().parseText(xml)
    root.listofthings.thing[0].replaceNode ( { thing(id:101, name:'bar') })
    root.listofthings.appendNode  ( { thing(id:102, name:'baz') })

    def outputBuilder = new groovy.xml.StreamingMarkupBuilder()
    String result = outputBuilder.bind { mkp.yield root }
    print result
}

产生:

<container>
   <listofthings>
     <thing id='101' name='bar'/>
     <thing id='102' name='baz'/>
   </listofthings>
</container>

我真正想要的是在开始 of 事物清单,即替换调用的东西替换节点相反,它将在 id 100 的事物之前插入 id 101 的事物。如果说我有一个更长的列表,在第 n 个元素之后插入一个节点,我也会很好。

(顺便说一句,有没有办法以更易读的格式获得输出?StreamingMarkupBuilder 的输出最终都是一行文本;为了清楚起见,我在上面重新格式化了它)

编辑:我正在使用 1.7.5,如果重要的话,它与 Eclipse 捆绑在一起。


一种方法是提取thing将原始 xml 中的元素放入列表中,操作该列表,然后使用此新列表重建文档:

// function to take a single line xml output, and make it pretty
String renderFormattedXml( String xml ){
  def stringWriter = new StringWriter()
  def node = new XmlParser().parseText( xml )
  new XmlNodePrinter( new PrintWriter( stringWriter ) ).print( node )
  stringWriter.toString()
}

def xml = """<container>
               <listofthings>
                   <thing id="100" name="foo"/>
               </listofthings>
             </container>"""

def root = new XmlSlurper().parseText(xml)

def things = root.listofthings*.thing

// Insert one at pos 0
things.add( 0, { thing( id:98, name:'tim' ) } )

// And one at the end
things.add( { thing( id:999, name:'zebra' ) } )

// And one at position 1
things.add( 1, { thing( id:99, name:'groovy' ) } )

def outputBuilder = new groovy.xml.StreamingMarkupBuilder()
String result = outputBuilder.bind {
  container {
    listofthings {
      mkp.yield things
    }
  }
}
println renderFormattedXml( result )

打印

<container>
  <listofthings>
    <thing id="98" name="tim"/>
    <thing id="99" name="groovy"/>
    <thing id="100" name="foo"/>
    <thing id="999" name="zebra"/>
  </listofthings>
</container>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Groovy:如何在使用 XMLSlurper() 读取的 XML 元素列表的开头插入节点 的相关文章

随机推荐