Search code examples
c#xml-serialization

How can I deserialize a XML file without defining the parent node?


I know there is a lot of content regarding deserialization of xml files, but I have not found a solution so far. My XML looks like this

<Data>
    <Products>
        <Product name="product1" brand="brand1">
            <ProductValues>
                <ProductValue name="price" value="100"/> 
                <ProductValue name="stock" value="23"/>
            </ProductValues>
        </Product>
        <Product name="product2" brand="brand1">
            <ProductValues>
                <ProductValue name="price" value="100"/> 
                <ProductValue name="stock" value="23"/>
            </ProductValues>
        </Product>
        <Product name="product2" brand="brand1">
            <ProductValues>
                <ProductValue name="price" value="100"/> 
                <ProductValue name="stock" value="23"/>
            </ProductValues>
        </Product>
    </Products>

    ... <!-- And more products -->

</Data>

I have a Product and ProductValue class where the corresponding fields are marked as XmlAttribute

public class Product
{
    [XmlAttribute]
    public string name;
    [XmlAttribute]
    public string brand;
    public ProductValue[] ProductValues

    ... 
}

Everything works find, if I create a new class, which is called Data and has a field public Product[] products and I deserialize like this

XmlSerializer serializer = new XmlSerializer(typeof(Data));
using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
    Data data = (Data)serializer.Deserialize(stream);
}

I dont want to create an extra class for this and also not an extra field like here but only instanitate the serializer with an array type XmlSerializer serializer = new XmlSerializer(typeof(Product[])); to receive a local Product[]. But if I do so, I get the error <Data xmlns="> was not expected


Solution

  • As @Rand Random pointed out a possible dublicate, I looked at that question and finally git it working combining this and this.

    XmlReader reader = XmlReader.Create(path);
    reader.MoveToContent();
    reader.ReadToDescendant("Products");
    XmlSerializer serializer = new XmlSerializer(typeof(Product[]), new XmlRootAttribute() { ElementName = "Products" });
    
    var products = (Product[])serializer.Deserialize(reader);