繁体   English   中英

在c#循环中进行Xattribute

[英]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;
}

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

代码下面的输出:

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

您可以使用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()));
}

希望这可以帮助。

做了一些假设之后,我认为你的createXmlElement方法的这个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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM