2011-01-24 4 views
0

내가 다음과 같습니다 일부 DOM 긁어 페이지로 시도하고 발견하지 그러나XmlSlurper 노드

<span><p>text</p></span> 

을, 난 그냥 수없는 것 두 번째 시나리오에서 text을받는 방법을 찾아보십시오. 나는 여러 가지 방법을 시도하고, 여기에 내가 아래 작업을해야 무슨 생각했습니다

def html = slurper.parse(reader) 
Collection<NodeChild> nodes = html.'**'.findAll { it.name() == 'span' && [email protected] == 'style2' } 
... 
def descriptionNode = html.'**'.find { it.name() == 'span' && [email protected] == 'style20' } 
def innerNode = descriptionNode.'**'.find { it.name() == 'p' } 
def description 
if (innerNode?.size() > 0) 
{ 
description = innerNode.text() 
} 
else 
{ 
description = descriptionNode.text() 
} 

내가 필요로하는 동작을 취득 xmlslurper 사용에 대한 갈 필요가 어떻게 어떤 생각을?

답변

0

결과적으로 HTML은 유효하지 않았 음에 틀림 없습니다. Tagsoup는

<div> 
<span> 
</span> 
<p></p> 
</div> 

을 만들었지 만 방화범은
<div> 
<span> 
<p></p> 
</span> 
</div> 

어떤 끔찍한 버그

을 표시.

0

xpath : //span/text()을 사용해 보셨습니까? 태그가 지정된 p에 대해 계정을 두 번 쿼리해야 할 수도 있습니다.

3

주어진 span에 중첩 된 p이 있는지 확인하려는 것 같습니다. span 노드의 하위 노드를 반복하여 해당 사례를 확인할 수 있습니다. 예 :

def xml = """ 
<test> 
    <span>test1</span> 
    <span><p>test2</p></span> 
    <other><span>test3</span></other> 
    <other><span><p>test4</p></span></other> 
</test> 
""" 

def doc = new XmlSlurper().parseText(xml) 
def descriptions = [] 
doc.'**'.findAll { it.name() == 'span' }.each { node -> 
    if (node.children().find { it.name() == 'p' }) { 
      descriptions << node.p.text() 
    } else { 
      descriptions << node.text() 
    } 
} 
assert descriptions == ['test1', 'test2', 'test3', 'test4']