Obtain the line and column of an XML node

9

In this 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"?>
<root>
    <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" />
    </menu>
</root>

What I'm doing is recovering that configuration with Python and as you can see in the source [ full code]

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

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

    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 found? To improve the detail of my exceptions when an XML configuration is wrong.

    
asked by Richar Siri 19.12.2015 в 02:33
source

1 answer

2

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

Note that this library is only compatible with python 2 (not with 3) but it is already 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 devour 3 .

More information about sourceline in the documentation of the element in lxml .

I have also found this question (with answer) in SO in English where they ask for specific information of sourceline if you needed to apply it.

    
answered by 06.07.2016 в 15:17