rp
asked on
Xml Get subelements to Datagridview
I have this code but only return the first line of each element InvoiceNum. For ex. Invoicenum 154 has two lines, but i can get only one line, the first. How can get all lines from each invoice.
<Documents>
<Sales>
<Total>81678.600000</Total>
<Invoice>
<InvoiceNum>153</InvoiceNum>
<Date>2013-03-01</Date>
<Customer>2589</Customer>
<Line>
<ProductId>AT.02-2584</ProductId>
<Description>Product 1</Description>
<Quantity>1.000</Quantity>
<UnitPrice>265.140000</UnitPrice>
</Line>
</Invoice>
<Invoice>
<InvoiceNum>154</InvoiceNum>
<Date>2013-03-01</Date>
<Customer>2589</Customer>
<Line>
<ProductId>AT.02-2584</ProductId>
<Description>Product 1</Description>
<Quantity>1.000</Quantity>
<UnitPrice>265.140000</UnitPrice>
</Line>
<Line>
<ProductId>AT.02-2599</ProductId>
<Description>Product 2</Description>
<Quantity>1.000</Quantity>
<UnitPrice>85.100000</UnitPrice>
</Line>
</Invoice>
</Sales>
</Documents>
filepath1 = "C:\Users\Documents\WorkP\March2013.xml"
Dim XmlDoc As XDocument = RemoveXmlNamespace(XDocument.Load(filepath1))
Dim query = From xe In XmlDoc.Descendants("Invoice")
Where xe.Element("InvoiceNo").Value = "154"
Select New With {
.Factura = xe.Element("InvoiceNo").Value,
.Cliente = xe.Element("CustomerID").Value,
.Produto = xe.Element("Line").Element("ProductCode").Value
}
DataGridView1.DataSource = query.ToArray
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
now that i look at the xml there's no ProductCode element inside Line element.
did u mean u have ProductId?
did u mean u have ProductId?
ASKER
I have two xml files one with ProductCode and another with ProductId. I'm a little confused (with Linq and Collections), what should put where is "n" in the code ".Select(n=>n.Value) ".
I made a mistake, it should be:
The reason u got only the 1st one is cause u called xe.Element("Line") and not xe.Elements("Line").
xe.Element("Line") return the first one if exists.
.Produto = xe.Elements("Line").Select(n=>n.Element("ProductCode").Value)
this little linq code means loop through line elements and for each get productcode value.The reason u got only the 1st one is cause u called xe.Element("Line") and not xe.Elements("Line").
xe.Element("Line") return the first one if exists.
ASKER
Sorry. Something is wrong with me. With the code provided ".Produto = xe.Elements("Line").Select (n=>n.Elem ent("Produ ctCode").V alue)", an error occurs saying "n is not declared".
Sorry its c# i need to convert it to vb.net
Open in new window
i usedOpen in new window
so it returns for each line in the invoicenum, the ProductCode value.