首页 > 解决方案 > 如何使用 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>

标签: pythonxmllxmlpretty-print

解决方案


我认为你不能这样做... 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()

推荐阅读