我有一个从“编辑,粘贴特殊,将XML粘贴为类”生成的类。像解释here. Generating Data Type Classes from XML
一样XML:
<?xml version="1.0"?>
<Items version="1.0">
<Item InputFileName="G:\FileFile.txt">
<Position X="500" Y="100" Z="150"/>
</Item>
</Items>
类别:
namespace Produccion.ClassFile
{
/// <comentarios/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class Items
{
private ItemsItem[] itemField;
private decimal versionField;
/// <comentarios/>
[System.Xml.Serialization.XmlElementAttribute("Item")]
public ItemsItem[] Item
{
get
{
return this.itemField;
}
set
{
this.itemField = value;
}
}
/// <comentarios/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal version
{
get
{
return this.versionField;
}
set
{
this.versionField = value;
}
}
}
/// <comentarios/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class ItemsItem
{
private ItemsItemPosition positionField;
private string inputFileNameField;
/// <comentarios/>
public ItemsItemPosition Position
{
get
{
return this.positionField;
}
set
{
this.positionField = value;
}
}
/// <comentarios/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string InputFileName
{
get
{
return this.inputFileNameField;
}
set
{
this.inputFileNameField = value;
}
}
}
/// <comentarios/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class ItemsItemPosition
{
private decimal xField;
private decimal yField;
private decimal zField;
/// <comentarios/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal X
{
get
{
return this.xField;
}
set
{
this.xField = value;
}
}
/// <comentarios/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal Y
{
get
{
return this.yField;
}
set
{
this.yField = value;
}
}
/// <comentarios/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal Z
{
get
{
return this.zField;
}
set
{
this.zField = value;
}
}
}
}
我不知道如何用文件中的数据初始化这个类。
答案 0 :(得分:6)
反序列化是读取XML文档并构造一个强类型为文档的XML Schema(XSD)的对象的过程。
你会做这样的事情
XmlSerializer serializer = new XmlSerializer(typeof(Items));
// Declare an object variable of the type to be deserialized.
Items i;
using (Stream reader = new FileStream(filename, FileMode.Open))
{
// Call the Deserialize method to restore the object's state.
i = (Items)serializer.Deserialize(reader);
}