Reputation: 364
Hey guys i need some help getting all elements of an XML file into a variable.
this is my XML:
<?xml version="1.0"?>
<labels>
<label>
<product>Prod. 1</product>
<colour>947 - Gold</colour>
<size>15</size>
<barcode>INT0919890</barcode>
<amount>15</amount>
</label>
<label>
<product>Prod. 4</product>
<colour>942 - Silver</colour>
<size>66</size>
<barcode>INT0912390</barcode>
<amount>16</amount>
</label>
<label>
<product>Prod. 8</product>
<colour>947 - Gold</colour>
<size>19</size>
<barcode>INT0932490</barcode>
<amount>11</amount>
</label>
</labels>
how can i make it so my program gets the first label, puts it into variables so i can use my other functions. and then continues to the next??
Upvotes: 0
Views: 1410
Reputation: 236238
Parsing with LINQ to XML (return strongly typed anonymous objects):
var xdoc = XDocument.Load(path_to_xml_file);
var labels = from l in xdoc.Root.Elements()
select new {
Product = (string)l.Element("product"),
Colour = (string)l.Element("colour"),
Size = (int)l.Element("size"),
Barcode = (string)l.Element("barcode"),
Amount = (int)l.Element("amount")
};
Usage:
foreach(var label in labels)
{
// use label.Product etc
}
Upvotes: 3