E-factory
2024-09-01 23:34:47
E-factory为生成XML和HTML提供了一种简单而紧凑的语法
# coding:utf-8
from lxml.builder import E def CLASS(*args): # class is a reserved word in Python
return {"class":' '.join(args)} html = page = (
E.html( # create an Element called "html"
E.head(
E.title("This is a sample document")
),
E.body(
E.h1("Hello!", CLASS("title")),
E.p("This is a paragraph with ", E.b("bold"), " text in it!"),
E.p("This is another paragraph, with a", "\n ",
E.a("link", href="http://www.python.org"), "."),
E.p("Here are some reserved characters: <spam&egg>."),
etree.XML("<p>And finally an embedded XHTML fragment.</p>"),
)
)
) print(etree.tostring(page, pretty_print=True)) '''
输出:
<html>
<head>
<title>This is a sample document</title>
</head>
<body>
<h1 class="title">Hello!</h1>
<p>This is a paragraph with <b>bold</b> text in it!</p>
<p>This is another paragraph, with a
<a href="http://www.python.org">link</a>.</p>
<p>Here are some reserved characters: <spam&egg>.</p>
<p>And finally an embedded XHTML fragment.</p>
</body>
</html>
'''
基于属性访问的元素创建使为XML语言构建简单词汇表变得容易
from lxml.builder import ElementMaker # lxml only ! E = ElementMaker(namespace="http://my.de/fault/namespace",
nsmap={'p' : "http://my.de/fault/namespace"}) DOC = E.doc
TITLE = E.title
SECTION = E.section
PAR = E.par my_doc = DOC(
TITLE("The dog and the hog"),
SECTION(
TITLE("The dog"),
PAR("Once upon a time, "),
PAR("And then ")
),
SECTION(
TITLE("The hog"),
PAR("Sooner or later ")
)
) print(etree.tostring(my_doc, pretty_print=True)) '''
输出:
<p:doc xmlns:p="http://my.de/fault/namespace">
<p:title>The dog and the hog</p:title>
<p:section>
<p:title>The dog</p:title>
<p:par>Once upon a time, </p:par>
<p:par>And then </p:par>
</p:section>
<p:section>
<p:title>The hog</p:title>
<p:par>Sooner or later </p:par>
</p:section>
</p:doc>
'''
其中一个例子是模块lxml.html.builder,它为html提供了词汇表
在处理多个命名空间时,最好为每个命名空间URI定义一个ElementMaker
同样,请注意上面的示例如何在命名常量中预定义标记生成器
这使得将名称空间的所有标记声明放在一个Python模块中以及从那里导入/使用标记名常量变得非常容易
这样可以避免诸如输入错误或意外丢失名称空间之类的陷阱
最新文章
- Tomcat使用详解
- CentOS7 屏幕亮度的命令行管理
- mysql时间段内查询
- 15. 3Sum_左右开工,遍历找出符合目标的数字
- C#序列化与反序列化方式简单总结
- QQ授权登录
- 织梦(dedecms)系统常用全局变量调用标签及路径
- Lambda表达式和匿名内部类(I)
- Android学习----自适应国际化语言
- [置顶] android LBS的研究与分享(附PPT)
- php之图片处理类缩略图加水印
- PagerSlidingTabStrip的使用
- OC基础 文件管理
- 疯狂Android第二章:Adapter以及部分控件使用
- OCA读书笔记(13) - 性能管理
- 理解free命令
- No module named machinery
- 阿里巴巴开源前端框架--Weex实践
- The 2nd tip of DB Query Analyzer
- Ceph基础知识和基础架构认识
热门文章
- 常用eslint配置
- JS四种判断数据类型的方法:typeof、instanceof、constructor、Object.prototype.toString.call()
- 页面导入样式时,使用link和@import有什么区别
- 使用mongoshake进行oplog同步读取,解决乱码问题
- 原生js复制粘贴上传图片前后台代码,兼容firebox,chrome, ie11,亲测有效
- 基于Tomcat的GeoServer部署步骤
- 【转】CAP 定理的含义
- Python——面向对象(类)的基础疑难点
- Retrofit-草稿
- input输入框change和blur事件区别