[英]Xml serialization c#
無法理解我做錯了什么,結果集是空的。
我的代碼:
class Class1
{
public static object DeSerialize()
{
object resultObject;
XmlSerializer serializer = new XmlSerializer(typeof(PointsContainer));
using (TextReader textReader = new StreamReader(@"d:\point.xml"))
{
resultObject = serializer.Deserialize(textReader);
}
return resultObject;
}
}
[Serializable]
[XmlRoot("Points")]
public class PointsContainer
{
[XmlElement("Point")]
private List<Point> items = new List<Point>();
public List<Point> Items
{
get { return items; }
set { items = value; }
}
}
[Serializable]
public class Point
{
[XmlAttribute]
public bool x { get; set; }
[XmlAttribute]
public bool y { get; set; }
}
XML:
<Points>
<Point x="1" y="5"/>
<Point x="21" y="3"/>
<Point x="3" y="7"/>
</Points>
將[XmlElement]
屬性移動到屬性。
XmlSerializer忽略私有成員。
正如SLaks所說
你的Point對象也顯示兩個字段為bool但xml文件中的值至少是ints(21,3,5,7等)
bool變量可以是true或false,其整數值為1和0.因此,您的XML具有無效數據和/或您的類屬性的類型錯誤。
[XmlElement("Point")]
public List<Point> Items
{
get { return items; }
set { items = value; }
}
在你的觀點類中,x和y都不應該是bool。
解:
namespace XmlStackProblem
{
class Class1
{
public static void Main()
{
Points resultObject;
XmlSerializer serializer = new XmlSerializer(typeof(Points));
using (TextReader textReader = new StreamReader(@"d:\points.xml"))
{
resultObject = serializer.Deserialize(textReader) as Points;
}
}
}
[Serializable]
[XmlRoot(IsNullable = false)]
public class Points
{
[XmlElementAttribute("Point")]
public List<Point> Point
{
get; set;
}
}
[Serializable]
[XmlType(AnonymousType = true)]
public class Point
{
[XmlAttribute]
public int x
{
get;
set;
}
[XmlAttribute]
public int y { get; set; }
}
}
您可以使用返回對象類型的DeSerialize函數,如下例所示:
public T DeSerializeFromString<T>(string data)
{
T result;
StringReader rdr = null;
try
{
rdr = new StringReader(data);
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
result = (T)xmlSerializer.Deserialize(rdr);
}
catch (Exception)
{
throw;
}
finally
{
rdr.Close();
}
return result;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.