python – Get the line and column of an XML node


In that project I am defining object configurations in XML format. An example is this is the case of a contextual menu:

<?xml version="1.0" encoding="UTF-8"?>
    <menu name="remates" widget="uiRemates" onshow="showMenu" >
        <action name="add" target="add" title="Nuevo Remate" icon=":/crud/add" disabled="" shortcut="CTRL+Key_A" />
        <action name="remove" target="remove" title="Eliminar Remate" icon=":/crud/delete" disabled="" />
        <action name="remove_apuesta" target="removeApuesta" title="Eliminar Apuesta" icon=":/crud/delete" disabled="" />
        <action name="print_remate" target="printRemate" disabled="" title="Imprimir Remate" />

What I am doing is recovering that configuration with Python and as you see in the source [ complete code]

def configField(self, field_element):
    name = field_element.getAttribute('name')
    if not name:
        raise ModelConfigFieldnameError(

    if not name in self.model.field_keys:
        raise ModelConfigNotHasFieldError(

    index_column = self.model.field_keys.index(name)
    self.setHeader(field_element, index_column)

field_element is an object of type <class xml.dom.minidom.Element ..>

My question is, how to determine in which line and column that element is located? In order to improve the detail of my exceptions when an XML configuration is wrong.


You can use lxml to do it. This library gives you more information for each element of the xml and among them a field called sourceline which is exactly what you need.

Note that this library is only compatible with python 2 (not 3) but it already falls within the definition of your project.

To be even more specific, given your xml in root you can:

print root.find('remove').sourceline

And in your case that would return 3 .

More information on sourceline in the documentation for the element in lxml .

I have also found this question (with an answer) in SO in English where they ask for specific information about the sourceline in case you need it when applying it.

Scroll to Top