Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 强制ElementTree使用结束标记_Python_Xml_String_Python 2.7_Elementtree - Fatal编程技术网

Python 强制ElementTree使用结束标记

Python 强制ElementTree使用结束标记,python,xml,string,python-2.7,elementtree,Python,Xml,String,Python 2.7,Elementtree,而不是: <child name="George"/> 然后,由于我使用的是Python 2.7,我阅读并尝试了html方法,如下所示: ch = ET.tostring(ET.fromstring(ch), method='html') 但这给了: TypeError: Parse() argument 1 must be string or read-only buffer, not Element 我不知道我该怎么做才能解决它。有什么想法吗?如果您这样做,它在2.7中应该

而不是:

<child name="George"/>
然后,由于我使用的是Python 2.7,我阅读并尝试了html方法,如下所示:

ch = ET.tostring(ET.fromstring(ch), method='html')
但这给了:

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

我不知道我该怎么做才能解决它。有什么想法吗?

如果您这样做,它在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>
从xml.etree.ElementTree导入元素、子元素、tostring
父元素=元素('父')
ch=子元素(父元素,“子元素”)
ch.set('name','George')
打印到字符串(父级,方法='html')
#
打印到字符串(子对象,方法='html')
#

“在XML文件中,我需要:
“你真的不需要,除非你正在对XML做一些你不应该做的事情(比如稍后使用正则表达式来解析)。@Tomalak“其他人”需要这样做。他们到底在做什么,来证明这个要求?所以他们是在“解析”使用XML解析器以外的其他内容创建XML。我想知道为什么这些问题总是被错误地解决。哦,好吧-/对于lxml,
ch.text='
(空字符串)可以工作。看见
TypeError: Parse() argument 1 must be string or read-only buffer, not Element
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>