1

我正在用 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>节点,我的猜测是我需要第二个类,比如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;
}
4

1 回答 1

2

创建一个具有单个属性的子类,LogLevel然后在您的基类上创建一个新类型的日志记录属性。

于 2010-06-15T14:04:41.180 回答