python - 如何使用 ElementMaker 漂亮地打印使用布尔条件创建的 XML
问题描述
当我不想生成E.note()时,如何避免格式错误?
现在,当条件为True时一切正常,但当它为False时,它会在 xml 中引入空间,从而导致格式错误。
一种解决方案是使用etree.Subelement(xml, "note"),但我想避免这种情况,因为它迫使我继续对所有后续元素使用 etree。
Python 3
lxml:4.5.2
from lxml.builder import ElementMaker
import lxml.etree as et
E = ElementMaker()
condition = False
xml = E.topic(
E.first("first"),
E.note("Text I want sometimes") if condition else "",
E.third("third")
)
with open("result.xml", "wb") as f:
f.write(et.tostring(xml.getroottree(),
pretty_print=True,
xml_declaration=True,
encoding='utf-8',
standalone=False))
我得到的结果:
<?xml version='1.0' encoding='utf-8' standalone='no'?>
<topic><first>first</first><third>third</third></topic>
但我想要的结果是:
<?xml version='1.0' encoding='utf-8' standalone='no'?>
<topic>
<first>first</first>
<third>third</third>
</topic>
解决方案
我认为你不能这样做... if condition else ...
,你必须以更传统的方式来做
xml = E.topic()
xml.append(E.first("first"))
if condition:
xml.append(E.note("Text I want sometimes"))
xml.append(E.third("third"))
最终
xml = E.topic(
E.first("first"),
E.third("third")
)
if condition:
xml.insert(1, E.note('Text I want sometimes'))
完整的工作示例
from lxml.builder import E # ElementMaker
import lxml.etree as et
#E = ElementMaker()
# --- functions ---
def display(xml):
print(et.tostring(xml.getroottree(),
pretty_print=True,
xml_declaration=True,
encoding='utf-8',
standalone=False).decode())
def example_0():
xml = E.topic(
E.first("first"),
E.note("Text I want sometimes") if condition else "",
E.third("third")
)
display(xml)
def example_1():
xml = E.topic()
xml.append(E.first("first"))
if condition:
xml.append(E.note("Text I want sometimes"))
xml.append(E.third("third"))
display(xml)
def example_2():
xml = E.topic(
E.first("first"),
E.third("third")
)
if condition:
xml.insert(1, E.note('Text I want sometimes'))
display(xml)
# --- main ---
condition = False
example_0()
example_1()
example_2()
推荐阅读
- javascript - 如何删除我在 Javascript 中随机获得的结果
- image - 如何在UWP中获取圆形图像源或位图图像以裁剪椭圆形状的图像
- html - 不通过 url nodejs 传递值
- javascript - 如何使用Javascript手动计算excel函数MDURATION?
- python - 日期时间差
- python - 决策树:如何手动设置决策节点
- ruby-on-rails - 是否可以在 Rails 中的 Postgres 的 activerecord-import on_duplicate_key_update 选项中为冲突目标提供多个唯一索引?
- python - 我如何向 Telegram API“说”我成功收到了他们的 webhook 请求?
- c# - 如何将键和值从一个字典复制/传输到另一个新字典/列表?
- javascript - Json数组与javascript中的不同长度比较