Reputation: 327
I'm trying to show all the info I need from an XML to a datagridview1. The XML has a <Product>
tag that contains it's own attributes and several Elements with it's own Attributes.
It looks like this:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Import>
<Products>
<Product Id="1" Name="prodcut1">
<Prices price=10,10/>
<Barcodes barcode="123123123123"/>
</Product>
<Product Id="2" Name="Product2">
<Prices price=9,9/>
<Barcodes Barcode="123123123123"/>
</Product>
</Products>
</Import>
Since a datagridview as far as I know, cant show more than one table (ie. dataGrid1.DataSource = dataSet.Tables[1];
), I was trying with Linq and anonymous types to select whatever I want and show it in one line per <Product>
tag.
On the datagrid it should look like something like this:
id | Name | Barcode | Price
1 product1 123... 10,10
2 product2 123.... 9,9
So far I wrote this to show <Product>
and its attributes, 'id' and 'name':
XElement ProdXML = XElement.Load(@"C:\Export\ppp.xml");
var query = from st in ProdXML.Descendants("Product")
select new
{
Id = st.Attribute("Id").Value,
name = st.Attribute("Name").Value,
};
dataGridView1.DataSource = query.ToList();
Is there any way to retrieve Prices => Price
and Barcodes => barcode
inside the Select
?
Upvotes: 3
Views: 89
Reputation: 813
Try with xml deserializer, it will be easier to use. You can then convert into list objects and play with it.
something like:
string xml = "";//Get xml here
var serializer = new XmlSerializer(typeof(Import));
var import = (Import)serializer.Deserialize(xml);
Use System.Xml.Serialization
Namespace
The classes that you can use can be like:
[XmlRoot(ElementName = "Prices")]
public class Prices
{
[XmlAttribute(AttributeName = "price")]
public string Price { get; set; }
}
[XmlRoot(ElementName = "Barcodes")]
public class Barcodes
{
[XmlElement(ElementName = "barcode")]
public List<string> Barcode { get; set; }
}
[XmlRoot(ElementName = "Product")]
public class Product
{
[XmlElement(ElementName = "Prices")]
public Prices Prices { get; set; }
[XmlElement(ElementName = "Barcodes")]
public Barcodes Barcodes { get; set; }
[XmlAttribute(AttributeName = "Id")]
public string Id { get; set; }
[XmlAttribute(AttributeName = "Name")]
public string Name { get; set; }
}
[XmlRoot(ElementName = "Products")]
public class Products
{
[XmlElement(ElementName = "Product")]
public List<Product> Product { get; set; }
}
[XmlRoot(ElementName = "Import")]
public class Import
{
[XmlElement(ElementName = "Products")]
public Products Products { get; set; }
}
Upvotes: 2
Reputation: 1438
Yes, you only need to access the element:
XElement ProdXML = XElement.Load(@"C:\Export\ppp.xml");
var query = from st in ProdXML.Descendants("Product")
select new
{
Id = st.Attribute("Id").Value,
name = st.Attribute("Name").Value,
price = st.Element("Prices").Attribute("Price").Value,
barcode = st.Element("Barcodes").Attribute("Barcode").Value
};
dataGridView1.DataSource = query.ToList();
Upvotes: 2