gpt4 book ai didi

python - 如何在 Python 中获取 XML 根元素的内容?

转载 作者:数据小太阳 更新时间:2023-10-29 02:32:04 24 4
gpt4 key购买 nike

我有一个 XML 文件,例如:

<?xml version="1.0" encoding="UTF-8"?>
<root>
First line. <br/> Second line.
</root>

作为我想要得到的输出:'\nFirst line. <br/> Second line.\n'我只是想注意,如果根元素包含其他嵌套元素,它们应该按原样返回。

最佳答案

我想到的第一个:

from xml.etree.ElementTree import fromstring, tostring

source = '''<?xml version="1.0" encoding="UTF-8"?>
<root>
First line.<br/>Second line.
</root>
'''

xml = fromstring(source)
result = tostring(xml).lstrip('<%s>' % xml.tag).rstrip('</%s>' % xml.tag)

print result

# output:
#
# First line.<br/>Second line.
#

但这不是真正通用的方法,因为如果打开根元素 ( <root>) 包含任何属性,它就会失败。

更新:这种方法还有另一个问题。自 lstriprstrip匹配给定字符的任意组合,你可能会遇到这样的问题:

# input:
<?xml version="1.0" encoding="UTF-8"?><root><p>First line</p></root>

# result:
p>First line</p

如果你真的只需要开始和结束标签之间的文字字符串(正如你在评论中提到的),你可以使用这个:

from string import index, rindex
from xml.etree.ElementTree import fromstring, tostring

source = '''<?xml version="1.0" encoding="UTF-8"?>
<root attr1="val1">
First line.<br/>Second line.
</root>
'''

# following two lines are needed just to cut
# declaration, doctypes, etc.
xml = fromstring(source)
xml_str = tostring(xml)

start = index(xml_str, '>')
end = rindex(xml_str, '<')

result = xml_str[start + 1 : -(len(xml_str) - end)]

这不是最优雅的方法,但与前一种方法不同,它可以正确处理开始标记内的属性以及任何有效的 xml 文档。

关于python - 如何在 Python 中获取 XML 根元素的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6669420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com