Serializing List<string> to XML

Associate
Joined
3 Jan 2006
Posts
522
Location
The Undercroft
Going round in circles here so some help would be appreciated. (C#)

I'm trying to serialize an object, similar to the code below, to XML.
Code:
public class someObject
    {
        public string key { get; set; }
        public List<string> values;

        //constructor and stuff
    }
Code:
someObject obj1 = new someObject() { key = "test1" };
            obj1.add("Value 1");
            obj1.add("Value 2");
            obj1.add("Value 3");
XmlSerializer x = new XmlSerializer(obj1.GetType());
x.Serialize(Console.Out, obj1);

That bit is simple enough and produces XML which looks like:

Code:
<?xml version="1.0" ?> 
<someObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <values>
       <string>Value 1</string> 
       <string>Value 2</string> 
       <string>Value 3</string> 
    </values>
    <key>test1</key> 
</someObject>

My question is: Is it possible to change the name of the <string> elements to something else like <value>?? Its creating the name based on the list type (List<string>).
I've tried creating another object called 'Value' which just returns a string and using that as the List type but I just get an extra layer of nesting/grouping which isnt the XML structure I need.

Any alternative ways of doing this? Any suggestions appreciated thanks.
 
Last edited:
You could write your own routine to generate the XML. It's very easy.

I did do thet to begin with, and it works, but wanted to create a generic object serializer which I can just chuck an object at and it will create the XML. Will probably have to revert to the less adaptable code if I can't find a solution.
 
Hmm after reading my OP a few times I don't think there is a way to do exactly what i'm after and any work around would be too hacky.. so nevermind! :p
 
Piece O'Cake, here you go:
Code:
    public class someObject
    {
        
        public string key { get; set; }
        
        [XmlArray]
        [XmlArrayItem(ElementName="value")]
        public List<string> values;

        //constructor and stuff
    }
 
Piece O'Cake, here you go:
Code:
    public class someObject
    {
        
        public string key { get; set; }
        
        [XmlArray]
        [XmlArrayItem(ElementName="value")]
        public List<string> values;

        //constructor and stuff
    }

I <3 you! works perfectly, thanks so much :) So many possible attributes, I knew there would be some in there somewhere
 
Back
Top Bottom