views:

58

answers:

1

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"/>
+2  A: 

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)

Robert Harvey
Would just add that if you're trying to meet a particular schema, you can use xsd.exe to create classes that conform to that schema. See: http://msdn.microsoft.com/en-us/library/x6c1kb0s(VS.71).aspx
Martin Clarke