[英]XML Deserialization without a namespace
我在重新序列化沒有命名空間的XML時遇到了一些麻煩。 奇怪的是,我得到一個例外,說“XML文檔中存在錯誤(2,2)。”; 內部異常“command_strings xmlns =不是預期的。” 我在VS2008編碼。
我的XML
<?xml version="1.0" encoding="utf-8"?>
<command_strings version="1">
<commands>
<command cmd_id="1" state_id="1" label="On" cmd_type="F" cmd_string="1" />
</commands>
</command_strings>
我的課
public class Command
{
[System.Xml.Serialization.XmlAttribute("cmd_id")]
public int cmd_id { get; set; }
[System.Xml.Serialization.XmlAttribute("state_id")]
public int state_id { get; set; }
[System.Xml.Serialization.XmlAttribute("label")]
public string label { get; set; }
[System.Xml.Serialization.XmlAttribute("cmd_type")]
public string cmd_type { get; set; }
[System.Xml.Serialization.XmlAttribute("cmd_string")]
public string cmd_string { get; set; }
}
[System.Xml.Serialization.XmlRoot("commands_strings")]
public class CommandCollection
{
[System.Xml.Serialization.XmlAttribute("version")]
public int version { get; set; }
[XmlArray("commands")]
[XmlArrayItem("command", typeof(Command))]
public Command[] Command { get; set; }
}
public bool IsValidXML()
{
CommandCollection commandscollection = null;
XmlSerializer dserial = new XmlSerializer(typeof(CommandCollection));
using (StreamReader streamReader = new StreamReader(@"C:\123.xml"))
{
commandscollection = (CommandCollection)dserial.Deserialize(streamReader);
streamReader.Close();
}
}
試試這個反序列化。
Stream Read = null;
object m_Configuration = null;
try
{
FileInfo FI = new FileInfo("C:\\");
Read = FI.OpenRead();
XmlSerializer serializer = new XmlSerializer(typeof(CommandCollection));
m_Configuration = serializer.Deserialize(Read);
}
finally
{
if (Read != null)
{
Read.Close();
}
}
您也可以嘗試而不是將Root屬性放在CommandCollection之上,使用
[XmlType("commands_strings")]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.