开发者

Controlling XML Serialization of a List<> derived class

I'm converting a Dictionary object into a List<> derived class by means of the following two declarations:

[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));
    }
}

I intend to serialize SerializableDictionary by means of the following code:

SerializableDictionary log = new SerializableDictionary(contents);
using (StringWriter xmlText = new StringWriter())
{
    XmlSerializer xmlFormat =
        new XmlSerializer(typeof(SerializableDictionary), new XmlRootAttribute("Log"));
    xmlFormat.Serialize(xmlText, log);
}

Works fine, but I'm unable to change the XML formatting.

This XML document is intended to be sent to a xml database field and is not meant to be deserialized.

  • I'd rather have both Name and Value formatted as attributes of the LogItem element.

However any attempts at using XMLAttribute have resulted in Reflection or compilation errors. I'm at loss as to what I can do to achieve this requirement. Could someone please help?


you can annotate them with XmlAttribute:

[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() { }
}

This worked fine for me and produced the following XML (based on sample input):

<?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>


There must be something else going on besides what you are showing. I am able to compile and execute the above code both with and without the XmlAttribute attribute applied to the Name and Value properties.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜