【问题标题】:Force ElementTree to use closing tag强制 ElementTree 使用结束标签
【发布时间】:2019-03-14 00:06:45
【问题描述】:

而不是:

<child name="George"/>

在 XML 文件中,我需要:

<child name="George"></child>

一个丑陋的解决方法是将空格写为文本(不是空字符串,因为它会忽略它):

import xml.etree.ElementTree as ET
ch = ET.SubElement(parent, 'child')
ch.set('name', 'George')
ch.text = ' '

然后,由于我使用的是Python 2.7,所以我阅读了Python etree control empty tag format,并尝试了html方法,如下所示:

ch = ET.tostring(ET.fromstring(ch), method='html')

但这给了:

TypeError: Parse() argument 1 must be string or read-only buffer, not Element

我不确定我应该怎么做才能修复它。有什么想法吗?

【问题讨论】:

  • "在 XML 文件中,我需要:&lt;child name="George"&gt;&lt;/child&gt;" 你真的不需要,除非你对 XML 做了一些你不应该做的事情正在做(比如稍后使用正则表达式解析它)。
  • @Tomalak 这个“其他人”需要它。
  • 他们在做什么,确切地说,证明这一要求是合理的?
  • 所以他们正在使用 XML 解析器以外的东西“解析”XML。我想知道为什么这些问题似乎总是被错误地解决了。那好吧。 :-/
  • 使用 lxml,ch.text = ''(空字符串)有效。见stackoverflow.com/a/47817478/407651

标签: python xml string python-2.7 elementtree


【解决方案1】:

如果你这样做,它应该可以在 2.7 中正常工作:

from xml.etree.ElementTree import Element, SubElement, tostring

parent = Element('parent')
ch = SubElement(parent, 'child')
ch.set('name', 'George')

print tostring(parent, method='html')
#<parent><child name="George"></child></parent>

print tostring(child, method='html')
#<child name="George"></child>

【讨论】:

    猜你喜欢
    • 2014-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-29
    • 2017-08-23
    • 2014-04-22
    相关资源
    最近更新 更多