lxml.etree 教程4:Elements contain text

本文探讨了XML文档中文本的表示方式,包括文本作为唯一节点的情况和文本嵌入到不同元素内部的情况。同时,解释了如何使用.text和.tail属性来操作XML文档中的文本,并展示了如何通过tostring()函数来获取正确的文本顺序。

元素可以包含文本:

>>> root = etree.Element("root")
>>> root.text = "TEXT"

>>> print(root.text)
TEXT

>>> etree.tostring(root)
b'<root>TEXT</root>'

 在很多XML文档(数据中心文档)中,这是可以找到文本的唯一地方。它在树结构的底部,用一个叶标签来封装。
然而,如果XML是用来标记文本,比如(X)HTML,文本也可以出现在不同的元素中。在树结构的中间:

<html><body>Hello<br/>World</body></html>

这里,<br/>标签被文本包围。元素通过tail属性来支持。它包含这个元素直接跟随的文本,在下一个直接相连的元素之前。

>>> html = etree.Element("html")
>>> body = etree.SubElement(html, "body")
>>> body.text = "TEXT"

>>> etree.tostring(html)
b'<html><body>TEXT</body></html>'

>>> br = etree.SubElement(body, "br")
>>> etree.tostring(html)
b'<html><body>TEXT<br/></body></html>'

>>> br.tail = "TAIL"
>>> etree.tostring(html)
b'<html><body>TEXT<br/>TAIL</body></html>'

 .text和.tail属性足够用来代表一个XML文档中的任意文本。

>>> etree.tostring(br)
b'<br/>TAIL'
>>> etree.tostring(br, with_tail=False) # lxml.etree only!
b'<br/>'

 If you want to read only the text, i.e. without any intermediate tags, you have to recursively concatenate all text and tail attributes in the correct order. Again, the tostring() function comes to the rescue, this time using the method keyword:

>>> etree.tostring(html, method="text")
b'TEXTTAIL'

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值