【问题标题】:Accessing XML comment located before the root element访问位于根元素之前的 XML 注释
【发布时间】:2011-01-05 00:25:05
【问题描述】:

请帮我解决我的 lxml 问题。 如何从此文件中获取“评论 1”?

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

【问题讨论】:

  • IIRC,xml 解析器无法访问评论 1,因为它是评论。您可能只需要以文本形式读取文件。
  • 您打算接受答案吗?

标签: python xml comments lxml


【解决方案1】:

文档:the lxml tutorial,然后搜索“评论”

代码:

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

【讨论】:

    【解决方案2】:
    >>> 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 属性。

    【讨论】:

      猜你喜欢
      • 2017-12-26
      • 2016-12-05
      • 2020-07-19
      • 1970-01-01
      • 1970-01-01
      • 2016-04-04
      • 1970-01-01
      • 1970-01-01
      • 2012-11-01
      相关资源
      最近更新 更多