强制ElementTree使用结束标记

2024-04-24 14:36:18 发布

您现在位置:Python中文网/ 问答频道 /正文

而不是:

<child name="George"/>

在XML文件中,我需要:

^{pr2}$

一个糟糕的解决方法是将空白写成文本(而不是空字符串,因为它会忽略它):

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

然后,由于我使用的是python2.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

我不知道我该怎么做才能修复它。有什么想法吗?在


Tags: 文件方法字符串name文本importchildhtml
1条回答
网友
1楼 · 发布于 2024-04-24 14:36:18

如果你这样做,它应该可以在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>

相关问题 更多 >