0
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;
}

我需要在循环中添加点。我怎样才能做到这一点?

以下代码的输出:

<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>
4

2 回答 2

0

做了一些假设后,我认为你的createXmlElement方法的这个重新设计的版本应该做你想做的事。它将创建过程分解XElement为多个离散的步骤。这应该更容易理解和理解。

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;
}

请注意,Point元素将如下所示...

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

而不是...

<Point> X='127' Y='71'</Point>
于 2015-02-22T08:00:41.403 回答
0

您可以使用LINQ to XML。用这个:

FreeList.Select(p => new XElement("Point",
                          new XAttribute("X", p.X),
                          new XAttribute("Y", p.Y))).ToArray();

而不是这个:

(for(int i = 0; i < FreeList.Count; i++)
{
    new XElement("Point",
                 new XAttribute("X", this.Pt1.X),
                 new XAttribute("Y", this.Pt1.Y));
}));

你的方法会更短:

public override XElement createXmlElement()
{
    return new XElement("Shape",
        new XAttribute("Name", "freeline"),
        new XElement("Pen_Details",
            new XAttribute("PenColor", this.PenColor.ToArgb().ToString("X")),
            new XAttribute("PenWidth", this.PenWidth),
            FreeList.Select(p => new XElement("Point",
                                  new XAttribute("X", p.X),
                                  new XAttribute("Y", p.Y))).ToArray()));
}

希望这可以帮助。

于 2015-02-22T07:54:56.817 回答