0

我有一个这样的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 的属性值中(即 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() }
 }

这是有效的。但是,我需要做这样的事情,而不是循环中的comapring文本

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

这我不正确

但是下面是正确的

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

但我想将选择限制为 classX 的节点

4

2 回答 2

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' ]

那是你想要的吗?

于 2012-11-22T11:55:48.853 回答
0

我想正确的方法是

mytest.'k'.find{ it.['@name']=="constname1"}

对其他一些 xml 链接做了类似的事情——> GPath Groovy

于 2013-02-05T10:34:17.883 回答