【发布时间】:2012-08-03 16:37:26
【问题描述】:
是否可以将内部 xml 元素反序列化为其等效类?我有以下 xml 片段:
<?xml version="1.0" encoding="utf-8" ?>
<tileconfiguration xmlns="http://somenamespace/tile-configuration">
<tile top_left_x="3" top_left_y="1" bottom_right_x="38" bottom_right_y="48">
<child>
</child>
</tile>
</tileconfiguration>
以及代表<tile /> 元素的等效类:
[System.Xml.Serialization.XmlRoot(ElementName = "tile")]
public class Tile : System.Xml.Serialization.IXmlSerializable
{
public System.Xml.Schema.XmlSchema GetSchema()
{
throw new NotImplementedException();
}
public void ReadXml(System.Xml.XmlReader reader)
{
throw new NotImplementedException();
}
public void WriteXml(System.Xml.XmlWriter writer)
{
throw new NotImplementedException();
}
}
问题是,每次我尝试反序列化 <tile_configuration /> 中的 <tile /> 实例时,XML 反序列化器都会抛出 文档 (2,2) 中的错误。
System.Xml.Serialization.XmlSerializer serial = new System.Xml.Serialization.XmlSerializer(typeof(Tile));
System.IO.TextReader t = new System.IO.StreamReader("c:\\temp\\deserial.xml");
Tile q = (Tile)serial.Deserialize(t);
如果我创建一个类来表示 <tile_configuration /> 并直接从中反序列化,它工作正常,调试器进入 TileConfiguration 类的 ReadXml 方法,然后我可以从中管理子 @987654330 的解析@(和后代)元素 - 但这需要每次重新读取整个 xml 文件。
简而言之;我是否需要读取和写入整个 XML 文件 - 每次我想使用序列化/反序列化时从根 xml 元素开始,或者有没有办法让我忽略多余的外部元素并直接将相关的子 xml 元素反序列化到他们的没有解析器卡盘错误的代码等效项?
非常感谢。
【问题讨论】:
标签: c# .net xml serialization deserialization