Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 控制列表的XML序列化<&燃气轮机;派生类_C#_Xml_Serialization - Fatal编程技术网

C# 控制列表的XML序列化<&燃气轮机;派生类

C# 控制列表的XML序列化<&燃气轮机;派生类,c#,xml,serialization,C#,Xml,Serialization,我通过以下两种声明将Dictionary对象转换为列表派生类: [Serializable] public class LogItem { public string Name { get; set; } public string Value { get; set; } public LogItem(string key, string value) { Name = key; Value = value; } public

我通过以下两种声明将Dictionary对象转换为列表派生类:

[Serializable]
public class LogItem
{
    public string Name { get; set; }
    public string Value { get; set; }

    public LogItem(string key, string value)
    {
        Name = key; Value = value;
    }

    public LogItem() { }
}

public class SerializableDictionary : List<LogItem>
{
    public SerializableDictionary(Dictionary<string, string> table)
    {
        IDictionaryEnumerator index = table.GetEnumerator();
        while (index.MoveNext())
        {
            Put(index.Key.ToString(), index.Value.ToString());
        }
    }

    private void Put(string key, string value)
    {
        base.Add(new LogItem(key, value));
    }
}
工作正常,但我无法更改XML格式

此XML文档旨在发送到XML数据库字段,而不是进行反序列化

  • 我宁愿有名字和价值 格式化为 LogItem元素

但是,任何使用XMLAttribute的尝试都会导致反射或编译错误。我不知道我能做些什么来达到这个要求。有人能帮忙吗?

您可以用
xmldattribute
对它们进行注释:

[Serializable]
public class LogItem
{
    [XmlAttribute]
    public string Name { get; set; }
    [XmlAttribute]
    public string Value { get; set; }

    public LogItem(string key, string value)
    {
        Name = key; Value = value;
    }

    public LogItem() { }
}
这对我来说很好,并生成了以下XML(基于示例输入):


除了您正在展示的内容之外,肯定还有其他事情在进行。我能够编译和执行上面的代码,无论是否将XmlAttribute属性应用于Name和Value属性

[XmlAttribute]
public string Name { get; set; }
[XmlAttribute]
public string Value { get; set; }

哦,天哪!我也一样。Value属性以前被声明为“对象”,而这正是上述操作不起作用的时候。我刚刚把它改成了字符串,因为我意识到了这个错误,但从来没有想到这会改变一切。非常感谢你Brokenglass是的有StellarEleven。实际上,我在LogItem中将Value属性声明为“object”,这时我出现了错误,XmlAttribute不起作用。然而,我实际上打算将其作为字符串,并在发布前几分钟进行了更改。我从未测试过,因为我不会想到这个简单的改变会带来如此大的不同。
<?xml version="1.0" encoding="utf-16"?>
<Log xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <LogItem Name="foo" Value="bar" />
  <LogItem Name="asdf" Value="bcxcvxc" />
</Log>
[XmlAttribute]
public string Name { get; set; }
[XmlAttribute]
public string Value { get; set; }