点击此处浏览总目录

ElementTree类

 elementtree主要是一个包含根节点的树的文档包装器

它提供了序列化和一般文档处理的两种方法

 

from lxml import etree

str = '''<?xml version="1.0"?>
     <!DOCTYPE root SYSTEM "test" [ <!ENTITY tasty "parsnips"> ]>
     <root>
       <a>&tasty;</a>
    </root>
    '''
root = etree.XML(str)

tree = etree.ElementTree(root)
print(tree.docinfo.xml_version) #输出:1.0
print(tree.docinfo.doctype) #输出:<!DOCTYPE root SYSTEM "test">

tree.docinfo.public_id = '-//W3C//DTD XHTML 1.0 Transitional//EN'
tree.docinfo.system_url = 'file://local.dtd'

print(tree.docinfo.doctype)
'''输出:
<!DOCTYPE root PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "file://local.dtd">
'''

print(etree.tostring(tree))
'''输出:
<!DOCTYPE root PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "file://local.dtd" [
<!ENTITY tasty "parsnips">
]>
<root>
  <a>parsnips</a>
</root>
'''

print(etree.tostring(tree.getroot()))
'''输出:
<root>
  <a>parsnips</a>
</root>
'''

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

posted @ 2019-10-30 15:59  立业的博客  阅读(754)  评论(0编辑  收藏  举报