Groovy xml基于父模式属性选择子节点属性

时间:2012-11-22 11:48:04

标签: groovy xml-parsing

我有像这样的xml结构

<JJJ version="2.0" >
<Data >
 <Object class="classX">
  <k name="constname1">variable1</p>
  <k name="constname2">variable2</p>
  <k name="constname3">variable3</p>
</Object>
 <Object class="classY">
  <k name="constname1">variable11</p>
  <k name="constname2">variable12</p>
  <k name="constname3">variable13</p>
</Object>

我需要选择ClassX节点以及包含constname1的atttribute值(即variable1

def parser = new XmlSlurper()
def mymo=records.'Data'.'Object';
def mytest =  mymo.findAll{it.@class.text()=="ClassX"};
mytest.each{
it.'p'.each{
  println  it.@name.text() +'-'+ it.text() }
 }

这很有效。但是,我不需要在循环中共同编写文本,而是需要做类似这样的事情

def testme= mytest.'k'.find{ it.@name.text()=="constname1"}

这我不对了

然而,以下是正确的

      println mymo.'k'.find{it.@name.text()=="constname1"}

但我想限制选择到classX的节点

2 个答案:

答案 0 :(得分:0)

更正你的xml以使它有效,给出:

def xml = '''<JJJ version="2.0" >
            |  <Data >
            |    <Object class="classX">
            |      <k name="constname1">variable1</k>
            |      <k name="constname2">variable2</k>
            |      <k name="constname3">variable3</k>
            |    </Object>
            |    <Object class="classY">
            |      <k name="constname1">variable14</k>
            |      <k name="constname2">variable15</k>
            |      <k name="constname3">variable16</k>
            |    </Object>
            |    <Object class="classX">
            |      <k name="constname1">variable7</k>
            |      <k name="constname2">variable8</k>
            |      <k name="constname3">variable9</k>
            |    </Object>
            |  </Data>
            |</JJJ>'''.stripMargin()

List var = new XmlSlurper().parseText( xml ).'**'.grep { 
  it.@name == 'constname1' && it.parent().@class == 'classX'
}

assert var == [ 'variable1', 'variable7' ]

是你想要的吗?

答案 1 :(得分:0)

我想正确的方法是

mytest.'k'.find {it。['@ name'] ==“constname1”}

与其他一些xml链接相似 - &gt; GPath Groovy