私のXMLファイルは次のようになります。
<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; }
}
バージョンは問題なく取得でき、階層は問題なく表示されますが、ItemオブジェクトのNameとAgeは常にnullです。XmlArrayの代わりにXmlElementを試しましたが、それも機能しません。
これを達成する方法についての助けは大歓迎です!!!
編集:私が示した例は、受け取ったXMLを単純化したものです。これは実際にはBINGAPIからロケーションRESTサービスへの呼び出しです。私が取得するXMLは、次のURLのXMLのようになります。
http://msdn.microsoft.com/en-us/library/ff701710.aspx
構造に入れようとしているのは、Location要素内の情報です。
私の実際のオブジェクトは次のようになります。
[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; }
}
うまくいけば、これは私がここで達成しようとしていることをさらに明確にするでしょう。
ありがとう!