Search code examples
c#xmlxml-serializationxml-validation

How to serialise an integer value?


As I'm just starting working with XML serialisation.

Currently I have a class, containing an "X" attribute:

public class Offset
{
    [XmlAttribute(AttributeName = "X")]
    public int X { get; set; }

XML serialisation generates something like:

<Offset ... X="0" .../>
              ^^^
               |
               +--- looks like a string

I would like the XML serialisation to look like:

<Offset ... X=0 ... />
              ^
              |
              +--- I'd like an integer.

In order to get this done, this is what I do:

public class Offset
{
    [XmlAttribute(AttributeName = "X", DataType = "int")]
    public int X { get; set; }

But again this is what my serialised XML looks like:

<Offset ... X="0" .../>  <!-- the double quotes are still there -->

There are two possibilities:

  • Either I'm doing something wrong and there is another way to remove those double quotes.
  • Either the required XML (without double quotes) is not valid. Problem is: I've used different XML validators (XML plugin from Notepad++, saying everything is ok, and another online one, saying just the opposite), so I'm not sure.

Can anyone tell me if the required XML format is valid and in case yes, what's the easiest way to tell the XML serialiser that an attribute must be handled as an integer (and in case of a floating point number, how to do this)?

Thanks in advance


Solution

  • The output that is already being generated is correct. The output you say you want: is not valid xml - attributes must use quotes. There is nothing to do here - the code and output is already fine, and the value is already an integer expressed as an xml attribute. This intent is valid in less strict contexts such as html, but not xml.

    Edit concerning official documentation about valid XML

    This link mentions that attributes must be quoted, so <Offset ... X=0 ... /> is not valid XML.