7

lxml に関する問題を解決するのを手伝ってください。このファイルから「コメント 1」を取得するにはどうすればよいですか?

<?xml version="1.0" encoding="windows-1251" standalone="yes" ?>
<!--Comment 1-->
<a>
   <!--Comment 2-->
</a>
4

2 に答える 2

11

ドキュメント: lxml チュートリアル、および「コメント」を検索

コード:

import lxml.etree as et

text = """\
<?xml version="1.0" encoding="windows-1251" standalone="yes" ?>
<!--Comment 1a-->
<!--Comment 1b-->
<a> waffle
   <!--Comment 2-->
   blah blah
</a>
<!--Comment 3a-->
<!--Comment 3b-->
"""
print "\n=== %s ===" % et.__name__
root = et.fromstring(text)

for pre in (True, False):
    for comment in root.itersiblings(tag=et.Comment, preceding=pre):
        print pre, comment

for elem in root.iter():
    print
    print isinstance(elem.tag, basestring), elem.__class__.__name__, repr(elem.tag), repr(elem.text), repr(elem.tail)

出力:

=== lxml.etree ===
True <!--Comment 1b-->
True <!--Comment 1a-->
False <!--Comment 3a-->
False <!--Comment 3b-->

True _Element 'a' ' waffle\n   ' None

False _Comment <built-in function Comment> 'Comment 2' '\n   blah blah\n'

コメント: xml.etree.cElementTree では機能しません

于 2010-01-14T11:17:20.377 に答える
6
>>> from lxml import etree
>>> tree = etree.parse('filename.xml')
>>> root = tree.getroot()
>>> print root.getprevious()
<!--Comment 1-->

または確かに(複数ある可能性があります):

>>> for i in root.itersiblings(tag=etree.Comment, preceding=True):
...     print i
...
<!--Comment 1-->

.textコメントのテキストを抽出する場合は、属性を使用します。

于 2010-01-14T10:59:54.630 に答える