如何基于元素或属性创建对象
本文关键字:属性 创建对象 元素 何基于 | 更新日期: 2023-09-27 18:15:52
需要帮助解析以下XML。我是Linq to XML的新手。我想解析所有的图片数据在一个单一的对象数组,我似乎找不到一种方法,
下面是一个示例xml,
<Object type="System.Windows.Forms.Form, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" name="Form1" children="Controls">
<Object type="System.Windows.Forms.PictureBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" name="PictureBox1" children="Controls">
<Property name="TabIndex">0</Property>
<Property name="Size">206, 152</Property>
<Property name="ImageLocation">C:'Documents and Settings'Administrator'Desktop'logo2w.png</Property>
<Property name="Location">41, 68</Property>
<Property name="TabStop">False</Property>
<Property name="Name">PictureBox1</Property>
<Property name="DataBindings">
<Property name="DefaultDataSourceUpdateMode">OnValidation</Property>
</Property>
</Object>
<Object type="System.Windows.Forms.PictureBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" name="PictureBox2" children="Controls">
<Property name="TabIndex">0</Property>
<Property name="Size">206, 152</Property>
<Property name="ImageLocation">C:'Documents and Settings'Administrator'Desktop'logo2w.png</Property>
<Property name="Location">42, 68</Property>
<Property name="TabStop">False</Property>
<Property name="Name">PictureBox2</Property>
<Property name="DataBindings">
<Property name="DefaultDataSourceUpdateMode">OnValidation</Property>
</Property>
</Object>
</Object>
我想访问PictureObjects[0].Location = 41, 68
, PictureObjects[1].Location = 42, 68
等值,我可以这样做吗?
我看到了几个示例,其中我可以基于节点名称创建这样的对象,而不是基于节点属性值?c# LINQ与XML,不能提取多个相同名称的字段到对象
有人可以指导或让我知道是否可行?
你可以这样开始,下面的代码只选择TabIndex和Size属性,显然添加其他不会是一个棘手的:
XDocument xdoc = XDocument.Load(@"path to a file or use text reader");
var tree = xdoc.Descendants("Object").Skip(1).Select(d =>
new
{
Type = d.Attribute("type").Value,
Properties = d.Descendants("Property")
}).ToList();
var props = tree.Select(e =>
new
{
Type = e.Type,
TabIndex = e.Properties
.FirstOrDefault(p => p.Attribute("name").Value == "TabIndex")
.Value,
Size = e.Properties
.FirstOrDefault(p => p.Attribute("name").Value == "Size")
.Value
});