How to deal with xmlns values while parsing an XML file?
<p>I have the following toy example of an XML file. I have thousands of these. I have difficulty parsing this file. </p>

<p>Look at the text in second line. All my original files contain this text. When I delete <code>i:type="Record" xmlns="http://schemas.datacontract.org/Storage"</code> from second line (retaining the remaining text), I am able to get <code>accelx</code> and <code>accely</code> values using the code given below. </p>

<p>How can I parse this file with the original text? </p>

<pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;ArrayOfRecord xmlns:i="http://www.w3.org/2001/XMLSchema-instance" i:type="Record" xmlns="http://schemas.datacontract.org/Storage"&gt;
  &lt;AvailableCharts&gt;
    &lt;Accelerometer&gt;true&lt;/Accelerometer&gt;
    &lt;Velocity&gt;false&lt;/Velocity&gt;
  &lt;/AvailableCharts&gt;
  &lt;Trics&gt;
    &lt;Trick&gt;
      &lt;EndOffset&gt;PT2M21.835S&lt;/EndOffset&gt;
      &lt;Values&gt;
        &lt;TrickValue&gt;
          &lt;Acceleration&gt;26.505801694441629&lt;/Acceleration&gt;
          &lt;Rotation&gt;0.023379150593228679&lt;/Rotation&gt;
        &lt;/TrickValue&gt;
      &lt;/Values&gt;
    &lt;/Trick&gt;
  &lt;/Trics&gt;
  &lt;Values&gt;
    &lt;SensorValue&gt;
      &lt;accelx&gt;-3.593643144&lt;/accelx&gt;
      &lt;accely&gt;7.316485176&lt;/accely&gt;
    &lt;/SensorValue&gt;
    &lt;SensorValue&gt;
      &lt;accelx&gt;0.31103436&lt;/accelx&gt;
      &lt;accely&gt;7.70408184&lt;/accely&gt;
    &lt;/SensorValue&gt;
  &lt;/Values&gt;
&lt;/ArrayOfRecord&gt;
</code></pre>

<p>Code to parse the data: </p>

<pre><code>import lxml.etree as etree
tree = etree.parse(r"C:\testdel.xml")
root = tree.getroot()

val_of_interest = root.findall('./Values/SensorValue')

for sensor_val in val_of_interest:
    print sensor_val.find('accelx').text
    print sensor_val.find('accely').text
</code></pre>

<p>I asked related question here: <a href="http://stackoverflow.com/questions/39402388/how-to-extract-data-from-xml-file-that-is-deep-down-the-tag">How to extract data from xml file that is deep down the tag</a> </p>

<p>Thanks </p>

<p>The confusion was caused by the following <em>default namespace</em> (namespace declared without prefix) :</p>

<pre><code>xmlns="http://schemas.datacontract.org/Storage"
</code></pre>

<p>Note that descendants elements without prefix inherit default namespace from ancestor, implicitly. Now, to reference element in namespace, you need to map a prefix to the namespace URI, and use that prefix in your XPath :</p>

<pre><code>ns = {'d': 'http://schemas.datacontract.org/Storage' }
val_of_interest = root.findall('./d:Values/d:SensorValue', ns)

for sensor_val in val_of_interest:
    print sensor_val.find('d:accelx', ns).text
    print sensor_val.find('d:accely', ns).text
</code></pre>

python xml