parsing an xml file for unknown elements using python ElementTree

放肆的年华 提交于 2019-12-14 03:48:38

问题


I wish to extract all the tag names and their corresponding data from a multi-purpose xml file. Then save that information into a python dictionary (e.g tag = key, data = value). The catch being the tags names and values are unknown and of unknown quantity.

    <some_root_name>
        <tag_x>bubbles</tag_x>
        <tag_y>car</tag_y>
        <tag...>42</tag...>
    </some_root_name>

I'm using ElementTree and can successfully extract the root tag and can extract values by referencing the tag names, but haven't been able to find a way to simply iterate over the tags and data without referencing a tag name.

Any help would be great.

Thank you.


回答1:


from lxml import etree as ET

xmlString = """
    <some_root_name>
        <tag_x>bubbles</tag_x>
        <tag_y>car</tag_y>
        <tag...>42</tag...>
    </some_root_name> """

document = ET.fromstring(xmlString)
for elementtag in document.getiterator():
   print "elementtag name:", elementtag.tag

EDIT: To read from file instead of from string

document = ET.parse("myxmlfile.xml")



回答2:


>>> import xml.etree.cElementTree as et
>>> xml = """
...    <some_root_name>
...         <tag_x>bubbles</tag_x>
...         <tag_y>car</tag_y>
...         <tag...>42</tag...>
...     </some_root_name>
... """
>>> doc = et.fromstring(xml)
>>> print dict((el.tag, el.text) for el in doc)
{'tag_x': 'bubbles', 'tag_y': 'car', 'tag...': '42'}

If you really want 42 instead of '42', you'll need to work a little harder and less elegantly.




回答3:


You could use xml.sax.handler to parse the XML:

import xml.sax as sax
import xml.sax.handler as saxhandler
import pprint

class TagParser(saxhandler.ContentHandler):
    # http://docs.python.org/library/xml.sax.handler.html#contenthandler-objects
    def __init__(self):
        self.tags = {}
    def startElement(self, name, attrs):
        self.tag = name
    def endElement(self, name):
        if self.tag:
            self.tags[self.tag] = self.data
            self.tag = None
            self.data = None
    def characters(self, content):
        self.data = content

parser = TagParser()
src = '''\
<some_root_name>
    <tag_x>bubbles</tag_x>
    <tag_y>car</tag_y>
    <tag...>42</tag...>
</some_root_name>'''
sax.parseString(src, parser)
pprint.pprint(parser.tags)

yields

{u'tag...': u'42', u'tag_x': u'bubbles', u'tag_y': u'car'}



回答4:


This could be done using lxml in python

from lxml import etree

myxml = """
          <root>
             value
          </root> """

doc = etree.XML(myxml)

d = {}
for element in doc.iter():
      key = element.tag
      value = element.text
      d[key] = value

print d


来源:https://stackoverflow.com/questions/8817283/parsing-an-xml-file-for-unknown-elements-using-python-elementtree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!