Python 解析 XML 文本

4 投票
4 回答
13419 浏览
提问于 2025-04-16 11:54

我想在Python中解析XML,但我希望直接用字符串来解析,而不是从文件中读取。有人能帮我实现这个吗?

4 个回答

2

你也可以使用 (xml.etree.cElementTree) 这个模块。

import xml.etree.cElementTree as ET

aElement = ET.fromstring('<Root id="UUID_1"><Item id="id_Item" /></Root>')

See Python help document
Each element has a number of properties associated with it:
  a tag which is a string identifying what kind of data this element represents (the element type, in other words). 
  a number of attributes, stored in a Python dictionary. 
  a text string. 
  an optional tail string. 
  a number of child elements, stored in a Python sequence 
3

你可以使用:xml.dom.minidom.parseString(text)

这个方法会为字符串创建一个StringIO对象,然后把这个对象传给解析函数。

你也可以用同样的方法,使用StringIO来配合其他任何需要文件样式对象的XML解析器。

import StringIO
your_favourite_xml_parser.parse(StringIO.StringIO('<xml>...</xml>'))
13

从一个文件中,通常你可以这样做:

from xml.dom import minidom                                          
xmldoc = minidom.parse('~/diveintopython/common/py/kgp/binary.xml')  

对于一个字符串,你可以把它改成:

from xml.dom import minidom                                          
xmldoc = minidom.parseString( Your string goes here )  

撰写回答