melculetz
melculetz

Reputation: 1971

User Defined XML Serialization

I have the following structure in C#:

[Serializable]
public struct Line
   {
        public Line(Point startPoint, Point endPoint)
        {
            StartPoint = startPoint;
            EndPoint = endPoint;
        } 
        public Point StartPoint;
        public Point EndPoint;
    }

which I use in another class, that is XmlSerializable

[XmlRootAttribute("Drawing")]
public Drawing
{
    [XmlElement("Line")]
    List<Line> lines;   

    //other members...
}

By serializing the Drawing class, I get an xml that describes a Line like this:

<Line>
    <StartPoint>
        <X>13</X>
        <Y>33</Y>
    </StartPoint>
    <EndPoint>
        <X>43</X>
        <Y>63</Y>
    </EndPoint>
</Line>

Is there any way of specifying the xml serialization tags so that a Line is generated in this format:

<Line StartPointX="13" StartPointY="33" EndPointX="43" EndPointY="63"/>

Upvotes: 1

Views: 335

Answers (1)

Robert Harvey
Robert Harvey

Reputation: 180788

Put [XmlAttribute] above your X and Y properties (not shown in your example). That should cause them to serialize as attributes instead of elements, and will produce the following XML:

<Line>
    <StartPoint X="13" Y="33" />
    <EndPoint X="43" Y="63" />
</Line>

If you are committed to your example output exactly as you specified, you will also have to restructure your object so that your X and Y attributes are named properly, like this:

[Serializable]
public struct Line
{
    [XmlAttribute]        
    public int StartPointX
    [XmlAttribute]        
    public int StartPointY
    [XmlAttribute]        
    public int EndPointX
    [XmlAttribute]        
    public int EndPointY
}

(Getters and Setters omitted for brevity)

Upvotes: 2

Related Questions