title: XPath in Visual Basic
body: <p>I am having a problem the "SelectSingleNode" function in Visual Basic.</p>
  
  <p>I have the following XML file:</p>
  
  <pre><code>&lt;sistema versao="1.02" xmlns="http://www.portalfiscal.inf.br/nfe"&gt;
  &lt;det&gt;
  &lt;prod&gt;
      &lt;cProd&gt;000085&lt;/cProd&gt;
      &lt;xProd&gt;MARTELO&lt;/xProd&gt;
      &lt;NCM&gt;73170090&lt;/NCM&gt;
      &lt;uCom&gt;UN&lt;/uCom&gt;
      &lt;vUnCom&gt;7.0000&lt;/vUnCom&gt;
  &lt;/prod&gt;
  &lt;imposto&gt;
      &lt;ICMS&gt;
          &lt;orig&gt;0&lt;/orig&gt;
          &lt;CST&gt;500&lt;/CST&gt;
      &lt;/ICMS&gt;
  &lt;/imposto&gt;
  &lt;/det&gt;
  &lt;/sistema&gt;
  </code></pre>
  
  <p>I need the value that is inside the node "cProd". In that case, "000085".</p>
  
  <p>I tried the following code:</p>
  
  <pre><code>    Public Sub importacao()
      Dim arquivos = CheckedListBox1.CheckedItems
      Dim total = arquivos.Count
  
      Dim nome_produto As String
  
      For i As Integer = 0 To total - 1
          Dim xml As New XmlDocument
  
          xml.Load(arquivos.Item(i))
  
          nome_produto = xml.ChildNodes(0).ChildNodes(0).ChildNodes(0).SelectSingleNode("cProd").InnerText
  
      Next
  
  End Sub
  </code></pre>
  
  <p>In "arquivos" is a CheckBoxList with the paths of the XML files.</p>
  
  <p>That returns the error "Object reference not set to an instance of an object." Because "SelectSingleNode("cProd")" is returning a null value.</p>
  
  <p>I think I'm placing the XPath incorrectly. Could someone help me?</p>
  
  <p>Thank you and sorry for my english.</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>It worked, I used a function to remove the namespaces (source: <a href="http://rprateek.blogspot.com.br/2011/01/how-to-remove-xmlns-namespace-from-xml.html" rel="nofollow">http://rprateek.blogspot.com.br/2011/01/how-to-remove-xmlns-namespace-from-xml.html</a>). And then I could use the following: <code>xml.ChildNodes(0).SelectSingleNode("//cProd").InnerText</code></p>
  
  <p>Just one more thing. What would be the most practical way of dealing with errors that may be caused if the tag "cProd" (or another one), does not exist in the file? For example, in some files, will not have the tag "NCM". Maybe I can verify if the tag exists with "GetElementsByTagName()"?</p>
  
  <p>Thank you all.</p>