1

I'm trying to serialize a set of classes to match a particular XML schema.

This schema has a lot of single element items (i.e., they don't themselves contain nested elements), for example:

<Product>Toy</Product>

The problem is that each element is potentially repeating, and optionally has up to six attributes, for example:

<Product language="eng>Toy</Product>

I thought I'd just create classes for these elements:

public class Product
{
    [XmlElement("Product")]
    public string Name { get; set; }

    [XmlAttribute("language")]
    public string Language { get; set; }
}

Trouble is, and I realised this would be an issue, the XML output it produces looks like this:

  <Product>
    <Product>Book</Product>
  </Product>
  <Product language="eng">
    <Product>Toy</Product>
  </Product>

The serializer is picking up on the name of the class, so you get duplication. I need it to look like this:

    <Product>Book</Product>
    <Product language="eng">Toy</Product>

Is there any way of getting this to work using this sort of method or do I need to rethink?

Also, if I can get it to work like this, am I going to get problems when deserializing?

Maybe I'm just going about it the wrong way, and there's a much better method for handling this sort of situation?

RichardJ
  • 95
  • 1
  • 2
  • 9
  • 1
    Use [`[XmlText]`](https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmltextattribute.aspx) instead of `[XmlElement("Product")]`. See [Using XmlSerializer to create an element with attributes and a value but no sub-element](https://stackoverflow.com/q/3524224/3744182). – dbc Feb 06 '18 at 02:01

0 Answers0