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>发布于 2015-02-22 15:54:57
您可以使用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-22 16:00:41
在做了一些假设之后,我认为这个修改过的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>https://stackoverflow.com/questions/28655005
复制相似问题