我有XML文档:
<?xml version="1.0" encoding="utf-8" ?>
<Menu>
<MainMenu>
<Meal>Example1</Meal>
<Meal>Example1</Meal>
<Meal>Example1</Meal>
<Meal>Example1</Meal>
<Meal>Example1</Meal>
<Meal>Example1</Meal>
</MainMenu>
</Menu>
我想把它反序列化为课程MainMenu
中的列表:
[Serializable()]
public class MainMenu
{
[System.Xml.Serialization.XmlElementAttribute("Meal")]
private List<string> Meal;
public MainMenu()
{
Meal = new List<string>();
}
}
按方法:
private void MenuDeserializer()
{
MainMenu mainMenu = null;
string path = "MenuXML.xml";
XmlSerializer serializer = new XmlSerializer(typeof(MainMenu));
StreamReader reader = new StreamReader(path);
reader.ReadToEnd();
mainMenu = (MainMenu)serializer.Deserialize(reader);
reader.Close();
}
这会将所有膳食反序列化到我的列表中吗?如果不是如何做到这一点?当我尝试调试时,我得到异常:XML文件(0,0)出错,这个(0,0)令人困惑,问题出在哪里以及如何解决?
答案 0 :(得分:1)
1 - 删除reader.ReadToEnd(),你从一开始就移动流,所以当你反序列化时,它会尝试从文件的末尾开始。
2 - 你需要从XML中删除外部Menu元素,你的类从MainMenu开始,所以你的xml也应该......
<?xml version="1.0" encoding="utf-8" ?>
<MainMenu>
<Meal>Example1</Meal>
<Meal>Example1</Meal>
<Meal>Example1</Meal>
<Meal>Example1</Meal>
<Meal>Example1</Meal>
<Meal>Example1</Meal>
</MainMenu>
答案 1 :(得分:0)
如果这是你的XML:
<?xml version="1.0" encoding="utf-8" ?>
<Menu>
<MainMenu>
<Meal>Example1</Meal>
<Meal>Example1</Meal>
<Meal>Example1</Meal>
<Meal>Example1</Meal>
<Meal>Example1</Meal>
<Meal>Example1</Meal>
</MainMenu>
</Menu>
我想把它反序列化为MainMenu类中的列表:
public class Menu
{
public MainMenu MainMenu{get;set;}
}
public class MainMenu
{
public List<string> Meal {get; set;}
public MainMenu()
{
Meal = new List<string>();
}
}
按方法:
private void MenuDeserializer()
{
Menu menu;
string path = "MenuXML.xml";
XmlSerializer serializer = new XmlSerializer(typeof(Menu));
using(StreamReader reader = new StreamReader(path))
{
menu = (Menu)serializer.Deserialize(reader);
}
}
这就是它的糟糕......
答案 2 :(得分:0)
您显示的XML可以反序列化:
[Serializable()]
[System.Xml.Serialization.XmlRoot("Menu")]
public class Menu
{
[XmlArray("MainMenu")]
[XmlArrayItem("Meal", typeof(string))]
public string[] MainMenu { get; set; }
}
public static void Main(string[] args)
{
XmlSerializer serializer = new XmlSerializer(typeof(Menu));
using(StreamReader reader = new StreamReader("MenuXML.xml"))
{
Menu menu = (Menu)serializer.Deserialize(reader);
reader.Close();
}
}