-1

I am using module xml.etree in Python3 to parse an xml file.

Here is a code sample:

# test.py
import xml.etree.ElementTree as ET

tree = ET.parse('test.xml')
root = tree.getroot()
node = root[0]
<?xml version="1.0.0"?>
<root>
    <node>test</node>
</root>

I want to get the position of node in test.xml, i.e., line 2, column 5 (or at least line2).

How can I implement this function?

I skimmed the methods of ElementTree class, but found no method for it.

OrthoPole
  • 3
  • 1

2 Answers2

0

Here is solution for your Question :

import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()
//here get the content of node
for child in root.iter('node'):
    print(str(child.text))

file_info = open('test.xml', 'r')
//here to find index
node_line_indexes = []


for i, line in enumerate(file_info.readlines()): 
    if 'node' in line:
        #extract line index for lines that contain //
        node_line_indexes.append(i )
print (node_line_indexes)

test.xml contains your xml data

and here is a good examples and explain for xml.etree with python

https://docs.python.org/3/library/xml.etree.elementtree.html

Hasan
  • 13
  • 3
0

xML doesn’t have a line number. If you know enumerate() you can easily do something similar, but with some restriction, e.g. comments:

import xml.etree.ElementTree as ET
from io import StringIO


xml ="""<?xml version="1.0.0"?>
<root>
    <node>test</node>
    <!-- comment -->
    <node>test</node>
</root>"""

f= StringIO(xml)

tree = ET.parse(f)
root = tree.getroot()

# If xml declaration is ln_no 0, but keep in mind comment lines are not counted.
for ln_no, elem in enumerate(root.iter(), start=1):
    print(ln_no, elem.tag)

Output:

1 root
2 node
3 node
Hermann12
  • 1,709
  • 2
  • 5
  • 14