Issue
I'm following along ElementTree tutorial and I get mostly the same results when working with the sample XML provided there, but I get unexpected results when using my own XML file.
For example, I'm trying to extract text from all XML tags named marketCode
. My sample XML file:
<process_config>
<input name="dataIn">
<filePattern>
<marketCode>nyse</marketCode>
<midfix/>
<format>csv</format>
</filePattern>
</input>
<input name="brokerIn">
<filePattern>
<marketCode>lse</marketCode>
<midfix>.CBOENL</midfix>
<format>csv</format>
</filePattern>
</input>
</process_config>
I use the following code to extract the data:
import xml.etree.ElementTree as ET, sys, os
my_file = 'test.xml'
tree = ET.parse(my_file)
root = tree.getroot()
for filePattern in root.findall('filePattern'):
marketCode = filePattern.find('marketCode').text
print(marketCode)
When I run the above code, I get an empty output. The expected output is as such:
nyse
lse
What might be wrong with the code?
Solution
filePattern
is not a direct child of the root element.
This works: root.findall('.//filePattern')
. This also works: root.findall('input/filePattern')
.
Answered By - mzjn
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.