XMLで配列内に配列を持つ構造をデシリアライズします。
- XML File
- C# code
を示します。
Stores.xml
<?xml version="1.0" encoding="utf-8"?>
<Stores>
<Store>
<Name>name1</Name>
<Area>
<description>name1 desc</description>
</Area>
<Area>
<description>name1 desc2</description>
</Area>
</Store>
<Store>
<Name>name2</Name>
<Area>
<description>name2 desc</description>
</Area>
<Area>
<description>name2 desc2</description>
</Area>
</Store>
<Store>
<Name>name3</Name>
<Area>
<description>name3 desc</description>
</Area>
<Area>
<description>name3 desc3</description>
</Area>
</Store>
<Store>
<Name>name4</Name>
<Area>
<description>name4 desc</description>
</Area>
<Area>
<description>name4 desc2</description>
</Area>
</Store>
</Stores>
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization; // add
namespace testDeserializeXml
{
class Program
{
static void Main(string[] args)
{
StoresXmlRead();
Console.ReadKey();
}
static private void StoresXmlRead()
{
using (System.IO.StreamReader reader = new System.IO.StreamReader(@"Stores.xml"))
{
XmlSerializer serializer = new XmlSerializer(typeof(Stores));
var value = (Stores)serializer.Deserialize(reader);
Console.WriteLine(string.Format("NumOfStore = {0}.", value.store.Length));
foreach (Store s in value.store)
{
Console.WriteLine(string.Format("Name = {0}", s.Name));
foreach (Area a in s.area)
{
Console.WriteLine(string.Format("description = {0}", a.description));
}
}
}
}
}
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public class Stores
{
[System.Xml.Serialization.XmlElementAttribute("Store")]
public Store[] store { get; set; }
}
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public class Store
{
public string Name { get; set; }
[System.Xml.Serialization.XmlElementAttribute("Area")]
public Area[] area { get; set; }
}
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public class Area
{
public string description { get; set; }
}
}