2016-08-11 12 views
1

한다고 가정 가진 XML을 노드를 찾을 수 :그루비 GPath 많은 조건

나는 조건에 의해 level1 노드를 찾을 수있다
<?xml version="1.0" encoding="UTF-8"?> 
<data> 
    <level0 id="2" t="1"> 
     <level1 id="lev1id21" att1="2015-05-12" val="121" status="0" year="2015" month="05" /> 
     <level1 id="lev1id22" att1="2015-06-13" val="132" status="0" year="2015" month="06" /> 
     <level1 id="lev1id23" att1="2015-07-11" val="113" status="0" year="2015" month="08" /> 
     <level1 id="lev1id23" att1="2015-07-11" val="114" status="0" year="2015" month="07" /> 
    </level0> 
</data> 

(우리는 많은 level0 형제를 가질 수 가정) : 각 level0를 들어

  1. 모든 찾기 att1 값을 갖는 'level1'노드 (Date을 yyyy-mm-dd로 해석 함)
  2. 노드 중 최대 값이 연도 및 월 속성의 값은 int로 해석됩니다.

예를 들어, val = "113"값을 가진 노드를 찾을 수 있습니다. GPath의 전문가가 아니기 때문에 올바른 Groovish 솔루션을 찾으십시오. 감사.

+0

귀하의 예상 된 결과가 기준을 일치하지 않습니다. 노드를'att1','year','month' 순으로 정렬하고 싶습니까? 이 경우 나는 당신의 데이터가 주어진'113'의 결과를 기대할 것입니다. –

+0

@thecodesmith_ 감사합니다. 예상 결과를 업데이트 했으므로 맞습니다. 113 번을 기대합니다. – lospejos

답변

2

예상되는 동작은 약간 분명하지 않지만 게시물에 대한 내 의견을 참조하십시오. 그러나 나는 데이터를 att1, 다음에 year, 다음으로는 month으로 정렬하고 최대 값을 찾는 것으로 가정합니다.

def date = { Date.parse('yyyy-MM-dd', [email protected]()) } 
def year = { [email protected]() } 
def month = { [email protected]() } 

운영자 <=> 그런 다음 "공간 배"를 사용하여 노드를 정렬 할 수 있습니다 : 당신이에 무슨 일이 일어나고 있는지 볼 수 있도록 Groovy의 방법으로 그것을 할

, 나는 몇 가지 헬퍼 메소드를 추출하는 것 (비교가 동일 할 때 발생하는) 비교를 수행하는,하고 "엘비스"연산자 ?:를 사용하는 최초의 0을 반환하는 경우 다음 단계의 비교를 수행합니다

def nodes = new XmlSlurper().parseText(xml).level0.level1 

def max = nodes.sort { a, b -> 
    date(a) <=> date(b) ?: 
      year(a) <=> year(b) ?: 
        month(a) <=> month(b) 
} .collect { [email protected] } .last() 

println max 
// Prints "113", given your data above 
1

현재로서는이 솔루션을 찾았습니다. 더 많은 정보가 필요하면 Groovish 방법이 있는지 알고 싶습니다.

def xml='''<?xml version="1.0" encoding="UTF-8"?> 
<data> 
    <level0 id="2" t="1"> 
     <level1 id="lev1id21" att1="2015-05-12" val="121" status="0" year="2015" month="05" /> 
     <level1 id="lev1id22" att1="2015-06-13" val="132" status="0" year="2015" month="06" /> 
     <level1 id="lev1id23" att1="2015-07-11" val="113" status="0" year="2015" month="08" /> 
     <level1 id="lev1id23" att1="2015-07-11" val="114" status="0" year="2015" month="07" /> 
    </level0> 
</data>''' 

def nodes = new XmlSlurper().parseText(xml).level0.level1.findAll {level1 -> 
    level1.max {lev1-> 
     Date.parse('yyyy-MM-dd',[email protected]()) 
    } 
} 
.each {level1 -> 
    level1.max { lev1 -> 
     [email protected]() as int 
    } 
}.max {level1 -> 
    [email protected]() as int 
}.collect() 

println "${nodes.count {it}}" 

nodes.each { n -> 
    println "val = ${[email protected]}" 
}