用lxml和Python解析XML
请帮助我解决lxml的问题用lxml和Python解析XML,python,lxml,Python,Lxml,请帮助我解决lxml的问题 (我是lxml的新手)。 如何从下一个文件中获取“注释1”: <?xml version="1.0" encoding="windows-1251" standalone="yes" ?> <!--Comment 1--> <a> <!--Comment 2--> </a> >>从lxml导入etree >>>tree=etree.parse('filename.xml') >>>root=tree
(我是lxml的新手)。
如何从下一个文件中获取“注释1”:
<?xml version="1.0" encoding="windows-1251" standalone="yes" ?>
<!--Comment 1-->
<a>
<!--Comment 2-->
</a>
>>从lxml导入etree
>>>tree=etree.parse('filename.xml')
>>>root=tree.getroot()
>>>打印root.getprevious()
或者可以肯定(可能不止一个):
>>对于root.itersiblings(tag=etree.Comment,preference=True)中的i:
... 打印i
...
如果要提取注释的文本,请使用.text
属性。文档:,并搜索“注释”
代码:
将lxml.etree作为et导入
text=”“”\
华夫饼
废话
"""
打印“\n===%s===%et.\u名称”__
root=et.fromstring(文本)
对于预输入(真、假):
对于root.itersiblings(tag=et.comment,previous=pre)中的注释:
印前、评论
对于根.iter()中的元素:
打印
打印isinstance(elem.tag,basestring),elem.\uuuuu类\uuuuuuu名称\uuuuuuu,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'
==lxml.etree===
真的
真的
假的
假的
True \u元素“a”华夫格\n“无”
错误\u注释“注释2”\n诸如此类\n
注释:不适用于xml.etree.cElementTreeIIRC,xml解析器无法访问注释1,因为它是注释。您可能必须以文本形式只读文件。是否计划接受答案?
>>> for i in root.itersiblings(tag=etree.Comment, preceding=True):
... print i
...
<!--Comment 1-->
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'