【发布时间】:2016-06-09 09:16:10
【问题描述】:
我正在从一个 XML 文件创建一个对象类,然后想分配一个不在 XML 文件中的字段,即:Color。
我的序列化如下:
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class pack
{
public steps steps { get; set; }
}
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class steps
{
readonly ChildCollection<step> Steps;
[System.Xml.Serialization.XmlElementAttribute("step")]
public Collection<step> StepList { get { return Steps; } }
}
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class step
{
[System.Xml.Serialization.XmlElementAttribute("step")]
public Collection<step> StepList { get { return Steps; } }
[System.Xml.Serialization.XmlAttributeAttribute("name")]
public string Name { get; set; }
[System.Xml.Serialization.XmlAttributeAttribute("id")]
public string Id { get; set; }
[System.Xml.Serialization.XmlAttributeAttribute("Color")]
public System.Drawing.Color Color { get; set; }
}
如您所见,在代码的最后一行中,我创建了一个颜色字段,然后在另一个函数中为其分配了一些可变颜色。
pack XmlFilePack = new pack();
using (FileStream stream = File.OpenRead(@"Steps_1.xml"))
{
try
{
XmlSerializer serializer = new XmlSerializer(typeof(pack));
XmlFilePack = (pack)serializer.Deserialize(stream);
}
finally
{
//close file
stream.Close();
}
}
但我一直用null 换成XmlFilePack。有谁知道错误在哪里?
更新:这是 XML 文件:
<pack >
<steps>
<step id ="12" name="S1" >
</step>
<step id ="1" name="S1" >
<step id ="2" name="S11" >
<step id ="3" name="S111" >
<step id ="5" name="S1121" >
</step>
</step>
</step>
<step id ="6" name="S12" >
<step id ="4" name="S112" >
<step id ="14" name="S112" >
</step>
</step>
</step>
</step>
</steps>
</pack>
【问题讨论】:
-
没有
Color属性是否可以工作?文件里有什么? -
是的,它确实工作得很好
-
System.Drawing.Color无法由XmlSerializer开箱即用地序列化。有关替代方案,请参阅Most elegant xml serialization of Color structure。 -
向我们展示 xml 节点
Color. -
@AlexanderPetrov 我已经添加了 XML 文件。我想提一下,XML 文件中没有
Color节点,我只是在序列化内部创建以供我的代码使用。
标签: c# .net xml serialization