Python etree control empty tag format

前端 未结 5 1591
小蘑菇
小蘑菇 2020-12-06 10:32

When creating an XML file with Python\'s etree, if we write to the file an empty tag using SubElement, I get:


5条回答
  •  鱼传尺愫
    2020-12-06 11:19

    Paraphrasing the code, the version of ElementTree.py I use contains the following in a _write method:

    write('<' + tagname)
    ...
    if node.text or len(node): # this line is literal
        write('>')
        ...
        write('' % tagname)
    else:
        write(' />')
    

    To steer the program counter I created the following:

    class AlwaysTrueString(str):
        def __nonzero__(self): return True
    true_empty_string = AlwaysTrueString()
    

    Then I set node.text = true_empty_string on those ElementTree nodes where I want an open-close tag rather than a self-closing one.

    By "steering the program counter" I mean constructing a set of inputs—in this case an object with a somewhat curious truth test—to a library method such that the invocation of the library method traverses its control flow graph the way I want it to. This is ridiculously brittle: in a new version of the library, my hack might break—and you should probably treat "might" as "almost guaranteed". In general, don't break abstraction barriers. It just worked for me here.

提交回复
热议问题