Read tag fields in XML VB.Net

Asked

Viewed 828 times

2

Good morning gentlemen,

I need to read a field that is inside an xml tag but I’m having difficulties, I need to do this to assemble a counter.

My project is to read the XML of a sale and assemble a fiscal coupon from it, but so far I have only managed to pull one item from the sale. Could you help me ?

Structure XML, in case I would need to read the field "nItem" that is in the tag "det", so maybe I could pull all the items:

<det nItem="1">
    <prod>
        <cProd>7898577370182</cProd>
        <xProd>J.WATANABE/COUVE MANTE</xProd>
        <vItem>0.99</vItem>
    </prod>
</det>
<det nItem="2">
    <prod>
        <cProd>66396</cProd>
        <xProd>GRANEL/ALHO KG</xProd>
        <vItem>1.62</vItem>
    </prod>
</det>

Structure VB.NET

Dim produto As New BindingSource
produto.DataSource = ds
produto.DataMember = "prod"
Dim descricao As String = produto.Current("xProd").ToString()
Dim quantidade As String = produto.Current("cProd").ToString()
Dim valorprod As String = produto.Current("vProd").ToString()
  • 1

    Is it an NF-e (Brazil)? You have an XML file to read from disk or is it in a string in memory?

1 answer

1


Here is an example that can help you in the solution:

Dim strXml As String =
    "<xml>
        <det nItem=""1"">
            <prod>
                <cProd>7898577370182</cProd>
                <xProd>J.WATANABE/COUVE MANTE</xProd>
                <vItem>0,99</vItem>
            </prod>
        </det>
        <det nItem=""2"">
            <prod>
                <cProd>66396</cProd>
                <xProd>GRANEL/ALHO KG</xProd>
                <vItem>1,62</vItem>
            </prod>
        </det>
    </xml>"
Dim xmlDoc As XmlDocument = New XmlDocument()
xmlDoc.LoadXml(strXml)

Dim xmlNodeList As XmlNodeList = xmlDoc.GetElementsByTagName("det")

After having the object xmlNodeList filled in, you can count the number of occurrences (if that’s what you want):

Dim nodeCount As Integer = xmlNodeList.Count

You can also go through each node and do additional treatment (get property value, child nodes, etc):

For Each node As XmlNode In xmlNodeList
    Dim value = node.Attributes.GetNamedItem("nItem").Value

    Dim cProd As String = Convert.ToString(node("prod")("cProd").InnerText)
    Dim xProd As String = Convert.ToString(node("prod")("xProd").InnerText)
    Dim vItem As Double = Convert.ToDouble(node("prod")("vItem").InnerText)
Next

Browser other questions tagged

You are not signed in. Login or sign up in order to post.