0

我有一个正在使用 pythonlxml.objectify库读取的 XML 文件。

我没有找到获取 XML 注释内容的方法:

<data>
  <!--Contents 1-->
  <some_empty_tag/>
  <!--Contents 2-->
</data>

我能够检索评论(有更好的方法吗?xml.comment[1]似乎不起作用):

xml = objectify.parse(the_xml_file).getroot()
for c in xml.iterchildren(tag=etree.Comment):
   print c.???? # how do i print the contets of the comment?
   # print c.text  # does not work
   # print str(c)  # also does not work

正确的方法是什么?

4

1 回答 1

1

您只需要将孩子转换回字符串即可提取评论,如下所示:

In [1]: from lxml import etree, objectify

In [2]: tree = objectify.fromstring("""<data>
   ...:   <!--Contents 1-->
   ...:   <some_empty_tag/>
   ...:   <!--Contents 2-->
   ...: </data>""")

In [3]: for node in tree.iterchildren(etree.Comment):
   ...:     print(etree.tostring(node))
   ...:
b'<!--Contents 1-->'
b'<!--Contents 2-->'

当然,您可能想要剥离不需要的包装。

于 2016-09-08T12:31:10.707 回答