2012-11-22 113 views
0

我有一個XML結構這樣Groovy的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節點並在含有atttribute constname1的那個值(即變量1

def parser = new XmlSlurper() 
def mymo=records.'Data'.'Object'; 
def mytest = mymo.findAll{[email protected]()=="ClassX"}; 
mytest.each{ 
it.'p'.each{ 
    println [email protected]() +'-'+ it.text() } 
} 

這是工作但是,代替然後在循環comapring文本,我需要做這樣的事情

def testme= mytest.'k'.find{ [email protected]()=="constname1"} 

這個我沒有得到正確的

但是下面的是正確

 println mymo.'k'.find{[email protected]()=="constname1"} 

但我想限制選擇的節點classX

回答

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 { 
    [email protected] == 'constname1' && it.parent()[email protected] == 'classX' 
} 

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

是你想要的嗎?

+0

那麼可以有更多的節點與ClassX,我需要使用.findAll;然後它不起作用;基本上我需要得到所有類的列表,其中包含類似於'def mytest = mymo.findAll {it。@ class.text()==「ClassX」};''然後在該文件上執行'find' –

+0

@alexcpn你能否更新你的問題,這樣的例子顯示你實際上有什麼和你需要的結果? –

+0

@alexcpn更新了我的答案...是否更接近? –

0

我想正確的辦法是

mytest.'k'.find

有沒有一些其他XML鏈接類似{它[ '@名字'] == 「constname1」} - >GPath Groovy