zoukankan      html  css  js  c++  java
  • lxml.etree 教程4:Elements contain text

    元素可以包含文本:

    >>> 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'
    
  • 相关阅读:
    Android开发之深入理解NFC(一)
    NetBeans找不到C/C++编译器
    【图解HTTP】第二章 简单的http协议
    长时间停留在calculating requirements and dependencies
    【图解HTTP】第一章 了解web及网络基础
    自定义DropDownMenu菜单
    【Android开发精要笔记】Android的Intent机制
    【操作系统】进程管理
    【Head First Java 读书笔记】(七)继承
    网易电面题总结
  • 原文地址:https://www.cnblogs.com/bluescorpio/p/3131184.html
Copyright © 2011-2022 走看看