[英]Looping through XDocument and getting values of child nodes
Here's what my XML file looks like. 这是我的XML文件的样子。
<PictureBoxes>
<P14040105>
<SizeWidth>100</SizeWidth>
<SizeHeight>114</SizeHeight>
<locationX>235</locationX>
<locationY>141</locationY>
</P14040105>
<P13100105>
<SizeWidth>100</SizeWidth>
<SizeHeight>114</SizeHeight>
<locationX>580</locationX>
<locationY>274</locationY>
</P13100105>
</PictureBoxes>
What I'm actually trying to do is loop through each control in my form and save the Size and Location property on an XML file. 我实际上想做的是遍历表单中的每个控件,并将Size和Location属性保存在XML文件中。 The
<P...
> Node is actually the name of my picturebox and I need to use that name as well. <P...
>节点实际上是我的图片框的名称,我也需要使用该名称。
After creating the XML, I want to try creating the picture boxes on the form again using the XML file. 创建XML之后,我想尝试再次使用XML文件在表单上创建图片框。 So what I need is get the name of the
<P...>
node and the values of the child nodes. 因此,我需要获取
<P...>
节点的名称和子节点的值。
You need to look at the FormLoad and FormClosing methods to load and respectively save data from/into the xml file. 你需要看看FormLoad和的FormClosing方法来加载和分别从/数据保存到XML文件。
In your FormLoad
method loop through the child elements of PictureBoxes
element and for each element create a PictureBox
and set it's values from the xml data as shown below: 在您的
FormLoad
方法中,循环浏览PictureBoxes
元素的子元素,并为每个元素创建一个PictureBox
并根据xml数据设置其值,如下所示:
protected override OnLoad(EventArgs e)
{
base.OnLoad(e);
var doc = XDocument.Load("path/to/xml/file");
foreach(var element in doc.Descendant("PictureBoxes").Elements())
{
var pb = new PictureBox();
pb.Name = element.Name.LocalName;
pb.Size.Width = Convert.ToInt32(element.Element("SizeWidth").Value));
// other properties here
this.Controls.Add(pb);
}
}
And in FormClosing
do the reverse thing - iterate over picture boxes and save the properties in xml: 然后在
FormClosing
执行相反的操作-遍历图片框并将属性保存在xml中:
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
var doc = new XDocument();
doc.Add(new XElement("PictureBoxes",
this.Controls.Where(c => c.GetType() == typeof(PictureBox))
.Select(pb => new XElement(pb.Name,
new XElement("SizeWidth", pb.Size.Width),
new XElement("location", pb.Location.X)))));
doc.Save("path/to/xml/file");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.