访问根元素之前的XML注释

8 投票
2 回答
7261 浏览
提问于 2025-04-15 18:01

请帮我解决我在使用lxml时遇到的问题。
我该如何从这个文件中获取“评论 1”?

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

2 个回答

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 属性。

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不兼容

撰写回答