我有一个使用python的lxml.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正确的方法是什么?
发布于 2016-09-08 20:31:11
您只需将子代转换回字符串即可提取注释,如下所示:
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-->'当然,您可能想要剥离不需要的包装。
https://stackoverflow.com/questions/39390653
复制相似问题