0
我的XML文件看起来像这样的数组元素中反序列化的数组元素:使用C#
<MyXml>
<Version> 9.3.2 </Version>
<Resources>
<Sets>
<ItemCollection>
<Item>
<Name> Name </Name>
<Age> 66 </Age>
</Item>
</ItemCollection>
</Sets>
</Resources>
我想要去的ItemCollection内的项目,但到目前为止,没有运气的话;这是我的代码如下所示:
Stream reader = new FileStream(fileLocation, FileMode.Open);
XmlSerializer s = new XmlSerializer(typeof(MyClass));
var items = s.Deserialize(reader) as MyClass;
而且我的对象是这样的:
[Serializable]
[XmlRoot("MyXml")]
public class MyClass
{
[XmlElement("Version")]
public string Version { get; set; }
[XmlElement("Resources")]
public List<Resources> Resources{ get; set; }
}
[Serializable]
public class Resources
{
[XmlElement("Sets")]
public List<Sets> Sets { get; set; }
}
[Serializable]
public class Sets
{
[XmlArray(ElementName = "ItemCollection")]
[XmlArrayItem("Item")]
public List<Item> Items { get; set; }
}
[Serializable]
public class Item
{
[XmlElement("Name")]
public string Name{ get; set; }
[XmlElement("Age")]
public string Age { get; set; }
}
我能得到的版本就好了,而且层次看起来不错,但姓名和年龄从项目对象始终为空。我已经尝试了XmlElement而不是XmlArray,但那也行不通。
任何帮助如何实现这一点将非常感谢!
编辑:我给出的例子简化了我收到的XML:它实际上是从BING API调用位置REST服务;该XML我收到看起来像一个在这个网址:
http://msdn.microsoft.com/en-us/library/ff701710.aspx
和我想要把我的结构位置 元素内的信息。
我真正的目标是这样的:
[Serializable]
[XmlRoot("Response")]
public class LocationService
{
[XmlElement("StatusCode")]
public string Code{ get; set; }
[XmlElement("ResourceSets")]
public List<ResourceSets> ResourceSets{ get; set; }
}
[Serializable]
public class ResourceSets
{
[XmlElement("ResourceSet")]
public List<ResourceSet> ResourceSet { get; set; }
}
[Serializable]
public class ResourceSet
{
[XmlArray(ElementName = "Resources")]
[XmlArrayItem("Location")]
public List<Location> Locations { get; set; }
}
[Serializable]
public class Location
{
[XmlElement("Latitude")]
public string Latitude{ get; set; }
[XmlElement("Longitude")]
public string Longitude{ get; set; }
}
希望这将进一步什么,我想在这里实现,甚至澄清。
谢谢!
因此,您可以生成该结构,但不能读回它? – jcolebrand 2011-02-11 02:48:24
您不需要Serializable属性,它旨在用于Formatter的派生序列化器(BinaryFormatter,SoapFormatter)。 XmlSerializer仅在公共属性上进行中继。即类可以通过XmlSerializer序列化,当且仅当它是公共的并且具有可访问的默认构造函数。而且您也不需要其中元素名称与属性名称相同的XmlElement属性。顺便说一句,你忘记了MyXml的结束标签?因为没有它,XML结构是无效的。 – 2011-02-11 02:54:09