Pithikos
Pithikos

Reputation: 20300

Python: Convert an xml/html element as defined by dict/list/string into an xpath string?

I want to define an xml element as a dictionary or string or list or whatever. This will be just a description of an xml element. It doesn't need to exist (that's why I don't use lxml or other libraries). For example having this

my_xml_element = {
                    "tag"       : "input",
                    "attribute" : ("value", "Login")
                 },

I want to get this

input[@value="Login"]

Does a module exist that can do that? I started doing my own implementation but want to be sure that I am not reinventing the wheel. Cheers!

Upvotes: 1

Views: 452

Answers (1)

tdelaney
tdelaney

Reputation: 77347

This is kinda what xml.etree.ElementTree is. Look at the Element() init routine:

def __init__(self, tag, attrib={}, **extra):
    attrib = attrib.copy()
    attrib.update(extra)
    self.tag = tag
    self.attrib = attrib
    self._children = []

A class is really just a dict wrapped with additional functionality. As your code matures, the dict will turn into a class, you'll add parent and clild references, implement a 'find' and finally.... end up with ElementTree.

Upvotes: 1

Related Questions