我正在尝试反序列化XML并从其元素中显示一个值,但是我收到了这个错误:
我刚从互联网上找到了一些样本,并试图根据我的需要编辑代码,但我相信我做得不对。请参阅下面的类和示例XML数据。您的意见和建议将受到高度赞赏。
的MainForm
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
public FileInfo ItemFile
{
get
{
return new FileInfo(@"C:\Data_120702-015842_440.xml");
}
}
void MainFormLoad(object sender, EventArgs e)
{
if (ItemFile.Exists)
{
List<Record> lst = new List<Record>();
XmlSerializer xml = new XmlSerializer(lst.GetType());
using (Stream s = ItemFile.OpenRead())
{
lst = xml.Deserialize(s) as List<Record>;
}
_items.Add(item);
MessageBox.Show(lst[0].Material_Code);
}
}
}
记录
public class Record
{
public string Material_Code;
public string Sub_Brand_Code;
public string Sub_Brand_Text;
public string Pack_Size_Code;
public string Pack_Size_Text;
public string Pack_Type_Code;
public string Pack_Type_Text;
public Record()
{
}
public Record(string Material_Code,
string Sub_Brand_Code,
string Sub_Brand_Text,
string Pack_Size_Code,
string Pack_Size_Text,
string Pack_Type_Code,
string Pack_Type_Text
)
{
this.Material_Code = Material_Code;
this.Sub_Brand_Code = Sub_Brand_Code;
this.Sub_Brand_Text = Sub_Brand_Text;
this.Pack_Size_Code = Pack_Size_Code;
this.Pack_Size_Text = Pack_Size_Text;
this.Pack_Type_Code = Pack_Type_Code;
this.Pack_Type_Text = Pack_Type_Text;
}
}
XML结构
<?xml version="1.0" encoding="UTF-8"?>
<MntProdHierAttrMDM>
<Record>
<Material_Code>60024517</Material_Code>
<Sub_Brand_Code>SB000416</Sub_Brand_Code>
<Sub_Brand_Text>Zwitsal</Sub_Brand_Text>
<Pack_Size_Code>PS000224</Pack_Size_Code>
<Pack_Size_Text>50ML</Pack_Size_Text>
<Pack_Type_Code>PT000042</Pack_Type_Code>
<Pack_Type_Text>BOTTLE</Pack_Type_Text>
</Record>
</MntProdHierAttrMDM>
答案 0 :(得分:2)
您需要将命名空间添加到xml中的指定元素。
每当我遇到反序列化问题时,我让序列化器为我解决问题;编写代码以序列化对象,并打开序列化程序生成的xml文件。
有关执行序列化的代码示例,请参阅http://msdn.microsoft.com/en-us/library/bdxxw552。
答案 1 :(得分:1)
[XmlRoot(ElementName = "MntProdHierAttrMDM")]
public class RecordCollection : List<Record>
{
public RecordCollection() : base(){}
public RecordCollection(int capacity) : base(capacity){}
}
void MainFormLoad(object sender, EventArgs e)
{
if (ItemFile.Exists)
{
RecordCollection lst = new RecordCollection();
XmlSerializer xml = new XmlSerializer(typeof(RecordCollection));
using (Stream s = ItemFile.OpenRead())
{
lst = xml.Deserialize(s) as RecordCollection;
}
_items.Add(item);
MessageBox.Show(lst[0].Material_Code);
}
}