私は C# で書いていて、IXmlSerializable
クラスを介して XML 構成ファイルを表現しようとしています。ただし、次のような、構成ファイルでネストされた要素を表す方法がわかりませんlogLevel
。
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<logging>
<logLevel>Error</logLevel>
</logging>
<credentials>
<user>user123</user>
<host>localhost</host>
<password>pass123</password>
</credentials>
<credentials>
<user>user456</user>
<host>my.other.domain.com</host>
<password>pass456</password>
</credentials>
</configuration>
タグLogLevel
のすべての可能な値を表す列挙型が呼び出されます。logLevel
内のタグcredentials
はすべて文字列として出力されます。と呼ばれる私のクラスでDLLConfigFile
は、次のものがありました。
[XmlElement(ElementName="logLevel", DataType="LogLevel")]
public LogLevel LogLevel;
<logLevel>
ただし、 XML ファイルのルート ノード内にないため、これは機能しません<logging>
。どうすればこれを行うことができますか?
ノードに関しては、次のようなプロパティを持つ<credentials>
2 番目のクラスが必要になると思います。CredentialsSection
[XmlElement(ElementName="credentials", DataType="CredentialsSection")]
public CredentialsSection[] AllCredentials;
編集: さて、Robert Loveの提案を試して、LoggingSection
クラスを作成しました。ただし、私のテストは失敗します:
var xs = new XmlSerializer(typeof(DLLConfigFile));
using (var stream = new FileStream(_configPath, FileMode.Open,
FileAccess.Read, FileShare.Read))
{
using (var streamReader = new StreamReader(stream))
{
XmlReader reader = new XmlTextReader(streamReader);
var file = (DLLConfigFile)xs.Deserialize(reader);
Assert.IsNotNull(file);
LoggingSection logging = file.Logging;
Assert.IsNotNull(logging); // fails here
LogLevel logLevel = logging.LogLevel;
Assert.IsNotNull(logLevel);
Assert.AreEqual(EXPECTED_LOG_LEVEL, logLevel);
}
}
私がテストしている設定ファイルには間違いなく<logging>
. クラスは次のようになります。
[Serializable]
[XmlRoot("logging")]
public class LoggingSection : IXmlSerializable
{
public XmlSchema GetSchema()
{
return null;
}
[XmlElement(ElementName="logLevel", DataType="LogLevel")]
public LogLevel LogLevel;
public void ReadXml(XmlReader reader)
{
LogLevel = (LogLevel)Enum.Parse(typeof(LogLevel),
reader.ReadString());
}
public void WriteXml(XmlWriter writer)
{
writer.WriteString(Enum.GetName(typeof(LogLevel), LogLevel));
}
}
[Serializable]
[XmlRoot("configuration")]
public class DLLConfigFile : IXmlSerializable
{
[XmlElement(ElementName="logging", DataType="LoggingSection")]
public LoggingSection Logging;
}