2011-10-06 2 views
0

올바른 해결책을 얻는 데 문제가 있습니다. <answer>이 = 99 인 경우 <question> 및 해당 하위를 삭제하려고합니다. 결과적으로 필터링 된 질문이있는 문자열이 필요합니다. 나는 다음과 같은 HTML 구조가 있습니다 ... 내가 XPath는 그것을 실현하려고 지금까지BeautifulSoup/LXML.html : 아이가 x처럼 보이면 태그와 자식을 삭제하십시오.

<html> 
<body>   
    <questionaire> 
    <question> 
    <questiontext> 
    Do I have a question? 
    </questiontext> 
    <answer> 
    99 
    </answer> 
    </question> 
    <question> 
    <questiontext> 
    Do I love HTML/XML parsing? 
    </questiontext> 
    <questalter> 
    <choice> 
     1 oh god yeah 
    </choice> 
    <choice> 
     2 that makes me feel good 
    </choice> 
    <choice> 
     3 oh hmm noo 
    </choice> 
    <choice> 
     4 totally 
    </choice> 
    </questalter> 
    <answer> 
     4 
    </answer> 
    </question> 
    <question> 
    </questionaire> 
</body> 
</html>  

을 ...하지만 iterparse를 lxml.html이없는 그것을 가지고? 고맙습니다!

답변

1

하실 것을 적극 수행합니다

from xml.dom import minidom 

doc = minidom.parseString(text) 
for question in doc.getElementsByTagName('question'): 
    for answer in question.getElementsByTagName('answer'): 
     if answer.childNodes[0].nodeValue.strip() == '99': 
      question.parentNode.removeChild(question) 

print doc.toxml() 

결과 :

<html> 
<body>   
    <questionaire> 

    <question> 
    <questiontext> 
    Do I love HTML/XML parsing? 
    </questiontext> 
    <questalter> 
    <choice> 
     1 oh god yeah 
    </choice> 
    <choice> 
     2 that makes me feel good 
    </choice> 
    <choice> 
     3 oh hmm noo 
    </choice> 
    <choice> 
     4 totally 
    </choice> 
    </questalter> 
    <answer> 
     4 
    </answer> 
    </question> 
    </questionaire> 
</body> 
</html> 
+0

안녕 매트 덕분에 ...이 매우 복잡 보이는

from lxml import etree html = etree.fromstring(html_string) questions = html.xpath('/html/body/questionaire/question') for question in questions: for elements in question.getchildren(): if element.tag == 'answer' and '99' in element.text: html.xpath('/html/body/questionaire')[0].remove(question) print etree.tostring(html) 
... 난 궁금가 BeautifulSoup 또는 lxml의 솔루션입니까? – Jurudocs

+0

html로 작동하도록 내 답변이 업데이트되었습니다. 끝에 ''이 추가되어 구문 분석 오류가 발생합니다. –

+0

대단히 고마워 ... 그 미니 돈 너무 무서운 찾았지만 너무 좋아 보인다! 개인적으로 나는 lxml을 선호합니다 ... 나는 두 개의 대답을 받아 들일 수 있었으면 좋겠다 ;-) – Jurudocs

1
답변에 대한