I am having a problem the "SelectSingleNode" function in Visual Basic.
I have the following XML file:
<sistema versao="1.02" xmlns="http://www.portalfiscal.inf.br/nfe">
<det>
<prod>
<cProd>000085</cProd>
<xProd>MARTELO</xProd>
<NCM>73170090</NCM>
<uCom>UN</uCom>
<vUnCom>7.0000</vUnCom>
</prod>
<imposto>
<ICMS>
<orig>0</orig>
<CST>500</CST>
</ICMS>
</imposto>
</det>
</sistema>
I need the value that is inside the node "cProd". In that case, "000085".
I tried the following 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
In "arquivos" is a CheckBoxList with the paths of the XML files.
That returns the error "Object reference not set to an instance of an object." Because "SelectSingleNode("cProd")" is returning a null value.
I think I'm placing the XPath incorrectly. Could someone help me?
Thank you and sorry for my english.
EDIT:
It worked, I used a function to remove the namespaces (source: http://rprateek.blogspot.com.br/2011/01/how-to-remove-xmlns-namespace-from-xml.html). And then I could use the following: xml.ChildNodes(0).SelectSingleNode("//cProd").InnerText
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()"?
Thank you all.