利用Python的动态性实现一个xml的编写器
- 用with块控制xml的上下文
- 借鉴一些templite里的code生成器的实现
- 重载+=运算符表示添加内容
- with块内就是一个加号
- 其实+=就是没有end tag的意思,而with块会自动生成end tag
- 所有的+都是append或者说insert的意思
- 通过重载@运算符控制插入的位置
2023年2月12日晚,实现了雏形:
2023年2月13日 实现了_
,觉得可以将项目名命名为xmlodash
哈哈哈哈
写这样的python代码
_ = Cursor()
with _ > "html":
with _ > "head":
_("title") + "标题"
with _ > "body" as body:
with _("img") as img:
img["src"] = "图片地址"
img["alt"] = "图片标题"
with _("div"):
for word in ["第一句", "第二句", "第三句"]:
_("p") + word
_("div")("div")("p")("ul")("li") + "还可以链式调用"
print(_)
生成这样的xml代码
<html>
<head>
<title>标题</title>
</head>
<body>
<img src="图片地址" alt="图片标题" />
<div>
<p>第一句</p>
<p>第二句</p>
<p>第三句</p>
</div>
<div>
<div>
<p>
<ul>
<li>还可以链式调用</li>
</ul>
</p>
</div>
</div>
</body>
</html>
源码见此