I have a xml file, in that file I have a tag named as SN and it occurs in multiple places.How do I write these line numbers as a list to another file.
Asked
Active
Viewed 68 times
0
-
What is your tag named as ? – Chetan_Vasudevan Sep 01 '17 at 15:38
-
what did you try so far? – Arpit Solanki Sep 01 '17 at 15:38
-
Tag is
which I missed – user8521874 Sep 01 '17 at 15:39 -
1Possible duplicate of [Is there a way to get a line number from an ElementTree Element](https://stackoverflow.com/questions/6949395/is-there-a-way-to-get-a-line-number-from-an-elementtree-element) – Lex Scarisbrick Sep 01 '17 at 15:42
-
Those methods did not work, so it is not a duplicate – user8521874 Sep 01 '17 at 15:48
1 Answers
1
So, you can use sourceline!Have a look at the example I have given below. Assuming you have a SN tag in xml file at multiple places.
from lxml import etree
context = etree.terparse(your_file_path)
line_number=[]
for action,elem in context:
if elem.tag=="SN" :
print(elem.text)
a=elem.sourceline
print(a)
line_number.append(a)
So here you have a empty list as line_number and when you go through the for loop fetching SN you can get its line number by sourceline and then append it to the list.

Chetan_Vasudevan
- 2,414
- 1
- 13
- 34
-
-
Now you can use file write to write these to a file.Hope you know those steps. – Chetan_Vasudevan Sep 01 '17 at 15:55