Reputation: 145
I have a xml file like:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE Chapter PUBLIC 'blub' 'blub.dtd'>
<Chapter>
<Tag>
<TagEntry y.validity.allowed="true" y.validity.mode="positive">
<!--Kommentar 1-->
<!--Kommentar 2-->
<!--Kommentar 3-->Inhalt 1<!--Kommentar 4--></TagEntry>
<TagEntry>
Inhalt 2 ergänzt <!--Kommentar 5-->mit Umlaut
</TagEntry>
<TagBase>
<!--Kommentar 6-->
<!--Kommentar 7-->Inhalt 3</TagBase>
<TagNothing>
Inhalt 3<!--Kommentar 8-->
</TagNothing>
</Tag>
</Chapter>
Now I want to iterate over the comments. I did it with lxml.etree as ET-tree:
comments = root.xpath('//comment()')
for comment in comments:
print(ET.tostring(comment))
But instead of printing all the comments without the text from the parent node, it prints this:
b'<!--Kommentar 1-->'
b'<!--Kommentar 2-->'
b'<!--Kommentar 3-->Inhalt 1'
b'<!--Kommentar 4-->'
b'<!--Kommentar 5-->mit Umlaut\n\t\t'
b'<!--Kommentar 6-->'
b'<!--Kommentar 7-->Inhalt 3'
b'<!--Kommentar 8-->\n\t\t'
Can someone explain to me, why this happens and how I can change maybe the xpath-expression to just return the comment nodes without the text being appended to the end of the comment.
Thank you!
Upvotes: 0
Views: 53
Reputation: 51002
The comment nodes are written with the tail
text included (the default; see https://lxml.de/api/lxml.etree-module.html#tostring).
To get rid of the tails, change
print(ET.tostring(comment))
to
print(ET.tostring(comment, with_tail=False))
If you are just interested in the content of the comments and not the markup, use this:
print(comment.text)
Upvotes: 3