Xattribute in a loop in c #

advertisements
public override XElement createXmlElement()
{
    XElement XShape = new XElement("Shape", new XAttribute("Name", "freeline"),
        new XElement("Pen_Details",
        new XAttribute("PenColor", this.PenColor.ToArgb().ToString("X")),
        new XAttribute("PenWidth", this.PenWidth),
        (for(int i = 0; i < FreeList.Count; i++)
        {
            new XElement("Point", new XAttribute("X", this.Pt1.X), new XAttribute("Y", this.Pt1.Y));
        }));

    return XShape;
}

I need to add the points in a loop. How can I do that?

The output below code:

<Shapes>
    <Shape Name="freeline">
        <Pen_Details PenWidth="2" PenColor="FFFF0000">
            <Point> X='127' Y='71'</Point>
            <Point> X='128' Y='71'</Point>
            <Point> X='130' Y='71'</Point>
        </Pen_Details>
    </Shape>
</Shapes>


Having made a few assumptions, I think that this reworked version of your createXmlElement method should do what you want. It breaks down the creation of the XElement into multiple, discrete, steps. This should make it easier to follow and understand.

public static XElement CreateXmlElement()
{
    var penDetails = new XElement("Pen_Details");
    penDetails.Add(new XAttribute("PenColor", PenColor.ToArgb().ToString("X")));
    penDetails.Add(new XAttribute("PenWidth", PenWidth));

    for (int i = 0; i < FreeList.Count; i++)
    {
        penDetails.Add(new XElement("Point", new XAttribute("X", FreeList[i].X), new XAttribute("Y", FreeList[i].Y)));
    };

    var shape = new XElement("Shape", new XAttribute("Name", "freeline"));
    shape.Add(penDetails);

    var shapes = new XElement("Shapes");
    shapes.Add(shape);

    return shapes;
}

Note that the Point elements will look like this...

<Point X='127' Y='71'></Point>

Rather than...

<Point> X='127' Y='71'</Point>