0

This is the xml file I am trying to parse. This file does not have a root tag.

<data txt="some0" txt1 = "some1" txt2 = "some2" >
     <data2>
            < bank = "SBI" bank2 = "SBI2" >
     <data2>
     <data3>
            <branch = "bang1" branch = bang"2" >
     <data3>
<data>

My script contains below lines. The below can be used to get the specific data after parsing it.

data = re.findall("<data txt=.*?</data>", re.DOTALL)
tree = ElementTree.fromstringlist(data)

I am unabale to parse this file because its not having root tag. please help me how to parse if the file is having no tag ??

2
  • Why are you using a regular expression in the first place? Just parse the whole document, leave the selection to ElementTree. Commented Jul 7, 2013 at 18:27
  • @MartijnPieters : The xml does not have root tag, hence i am not able to parse. Commented Jul 7, 2013 at 18:29

1 Answer 1

1

As pointed out in a comment already, you can just parse the whole thing. If the missing root element is the problem, you can grab the contents of the file as a string and then add an arbitrary root tag at the beginning and the end.

stringdata = "<myroot>%s</myroot>" % stringdata

and then parse the string.

EDIT:

In response to comment.

If you have one string, you'll want fromstring, but you'll almost certainly get the same error. Something else is going on. Try this ...

from xml.etree import ElementTree
stringdata = "<myroot>%s</myroot>" % stringdata
tree = ElementTree.fromstring(stringdata)

Then get what you need from tree.

Sign up to request clarification or add additional context in comments.

1 Comment

@MartijnPieters : i got the xml data in one variable now. i tried to parse it using above my two line script, but its throwing an error "'module' object has no attribute 'fromstringlist'" ? can you help me to parse this data ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.