Reputation: 9175
I have a problem getting to the right solution. I want to delete <question>
and its children if <answer>
is = 99. As a result, I need a string with the filtered questions. I have the following html structure:
<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>
So far i tried to realize it with xpath...but lxml.html has no iterparse...has it? Thanx!
Upvotes: 0
Views: 917
Reputation: 40223
This will do exactly what you need:
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()
Result:
<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>
Upvotes: 1
Reputation: 1132
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)
Upvotes: 1