[英]Xattribute in a loop in c#
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>
You can use LINQ to XML . 您可以使用LINQ to XML 。 Use this:
用这个:
FreeList.Select(p => new XElement("Point",
new XAttribute("X", p.X),
new XAttribute("Y", p.Y))).ToArray();
Instead of this: 而不是这个:
(for(int i = 0; i < FreeList.Count; i++)
{
new XElement("Point",
new XAttribute("X", this.Pt1.X),
new XAttribute("Y", this.Pt1.Y));
}));
And your method is going to be much more shorter: 而且你的方法会更短:
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()));
}
Hope this helps. 希望这可以帮助。
Having made a few assumptions, I think that this reworked version of your createXmlElement
method should do what you want. 做了一些假设之后,我认为你的
createXmlElement
方法的这个createXmlElement
版本应该做你想要的。 It breaks down the creation of the XElement
into multiple, discrete, steps. 它将
XElement
的创建分解为多个离散的步骤。 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
元素看起来像这样......
<Point X='127' Y='71'></Point>
Rather than... 而不是...
<Point> X='127' Y='71'</Point>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.