Search code examples
c#xmlxml-serializationxml-deserialization

C# XML deserialization to DataSet within one table


I'm making a custom XML parser to read/edit a set of XML documents (21). All of them are having their own XSD and are valid XML docs. The XSD files were converted to serializable *.cs classes with xsd.exe tool.

For clarification, I can read the XML succefully, but I can't read the child node attributes/value properly so it is displayed in the DataGridView (the attribute wPath in the resourceUrl node, see example below)

Since I don't have enough experiences w/XML and serialization, I'm uncertain about the following: Is .NET providing some built-in functionality to handle reading child node attributes/values or I should have to read it manualy?

In the following example, all the attributes and its values are succefully loaded in the DataSet/DataTable - except the resourceUrl node - the column is there, but the value is just the name of the type.

Example XML:

<?xml version='1.0' encoding="utf-8" ?>
<c:product_resourceUrls xmlns:sql="urn:schemas-microsoft-com:xml-sql" xmlns:c="http://example.com/data/scl/product_resourceUrl">
  <y0:product_resourceUrl xmlns:y0="http://example.com/data/scl/product_resourceUrl" ExternalProductId="90AI8-3I" ProductSKU="90AI8-3I" Name="/images/path_to_product_img.jpg">
    <y0:resourceUrl WPath="/images/path_to_product_img.jpg"/>
  </y0:product_resourceUrl>
</c:product_resourceUrls>

The expected output in the DataTable is row like this (I don't mind the column order):

     WPath       | ExternalProductId | ProductSKU |      Name
"/images/p..."   |    "90AI8-3I"     |   90AI8-3I | "/images/p..."

Thank you in advance for any relevant hint ^^


Solution

  • public class Product
    {
        public string ExternalProductId { get; set; }
        public string ProductSKU { get; set; }
        public string Name { get; set; }
        public string WPath { get;  set; }
    }
    

    Usage

    var doc = XDocument.Load(xml);
    var urls = doc.Root.Nodes().Cast<XElement>();
    
    List<Product> products = new List<Product>();
    
    foreach (XElement url in urls)
    {
        products.Add(new Product()
        {
            ExternalProductId = url.Attribute("ExternalProductId").Value,
            ProductSKU = url.Attribute("ProductSKU").Value,
            Name = url.Attribute("Name").Value,
            WPath = ((XElement)url.FirstNode).Attribute("WPath").Value,
        });
    }