LoginSignup
1
0

More than 3 years have passed since last update.

XmlSerializerで複数種類のエレメントのListを定義したい

Last updated at Posted at 2020-02-20

XmlSerializerで複数種類のエレメントのListを定義したい

設定ファイルなんかで Listを使うんだけど、設定内容はほとんど一緒なのに動作がちょっとだけ違うみたいな場合

PlantUML Web Server

こんな形にして

<?xml version="1.0" encoding="utf-8"?>
<Config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ConnectionString>hogehoge...</ConnectionString>
  <Suppliers>
    <Supplier>
      <Name>Nissin</Name>
      <Query>select * from...</Query>
      <AdditionalParameter />
    </Supplier>
    <SealCountSupplier>
      <Name>Maruchan</Name>
      <Query>select * from...</Query>
      <AdditionalParameter />
      <OptionalParameter>100</OptionalParameter>
    </SealCountSupplier>
  </Suppliers>
</Config>

こんな定義にしたい。

でも普通にXmlSerialiser.Deserialize()するとSealCountSupplierが復元されない。

そんなあなたに XmlArrayItemAttribute

XmlSerializer がシリアル化された配列で配置できる派生型を指定する属性を表します。
XmlArrayItemAttribute クラス (System.Xml.Serialization) | Microsoft Docs

    public class Config {
        public string ConnectionString{get;set;}
        public Config() { }

        [XmlArrayItem(Type = typeof(Supplier))]
        [XmlArrayItem(Type = typeof(SealCountSupplier))]
        public List<Supplier> Suppliers = new List<Supplier>();
    }

こうじゃ。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0