我刚开始使用xml序列化,我尝试了这些:
(1)在反序列化时抛出异常。 (2)也抛出异常 (3)不能正常工作。
非常感谢任何想法。提前谢谢。
1) const string XML = @"<?xml version=""1.0""?>
<DietPlan>
<Fruit>fig</Fruit>
<Veggie>Carrot</Veggie>
</DietPlan>";
[XmlRoot(ElementName = "DietPlan")]
public class TestData
{
[XmlElement("Fruit")]
public XmlElement Fruits { get; set; }
[XmlElement("Veggie")]
public XmlElement test { get; set; }
}
2) const string XML = @"<?xml version=""1.0""?>
<DietPlan>
<Fruit>fig</Fruit>
<Fruit>fig</Fruit>
<Veggie>Carrot</Veggie>
<Veggie>Carrot</Veggie>
</DietPlan>";
[XmlRoot(ElementName = "DietPlan")]
public class TestData
{
[XmlElement("Fruit")]
public List<XmlElement> Fruits { get; set; }
[XmlElement("Veggie")]
public List<XmlElement> test { get; set; }
}
3) const string XML = @"<?xml version=""1.0""?>
<DietPlan>
<Data>
<Fruit>fig</Fruit>
<Fruit>fig</Fruit>
<Veggie>Carrot</Veggie>
<Veggie>Carrot</Veggie>
</Data>
</DietPlan>";
[XmlRoot(ElementName = "DietPlan")]
public class TestData
{
public Datas Datas { get; set; }
}
public class Datas
{
[XmlElement("Fruit")]
public List<XmlElement> Fruits { get; set; }
[XmlElement("Veggie")]
public List<XmlElement> test { get; set; }
}
1)xml文件在我的上下文中有效! (虽然格式不正确)
2)这是我用来反序列化的代码!
public static void Deserialize()
{
var ms = new MemoryStream(Encoding.UTF8.GetBytes(XML));
var xs = new XmlSerializer(typeof(TestData));
var obj = (TestData)xs.Deserialize(ms);
}
编辑:(3)此处已有答案enter link description here
答案 0 :(得分:0)
如果您不需要类成员为XMLElement类型,请改用字符串:
[XmlRoot(ElementName = "DietPlan")]
public class TestData
{
[XmlElement("Fruit")]
public string Fruits { get; set; }
[XmlElement("Veggie")]
public string test { get; set; }
}