tags:

views:

146

answers:

5

Suppose I have a number of elements to store like:

fruitList = "apple", "orange", "banana", "kiwi", ...

How would you store these in XML?

<FruitList>"apple", "orange", "banana", "kiwi"</FruitList>

OR

<Fruits Type="Expensive" List="apple", "orange", "banana", "kiwi"> </Fruits>

Is there a better way?

Whatever method is chosen, how can I parse the list easily so that the parsing doesn't need to change if the formatting of the items is changed to something like:

<FruitList>
   "apple", 
   "orange",
   "banana",
   "kiwi"
</FruitList>
+15  A: 
<Fruits>
 <Fruit>Apple</Fruit>
 <Fruit>Orange</Fruit>
</Fruits>
Randolpho
Thanks, good idea.
Joan Venge
i would still recommend using the serializer. Construct an object that holds your metadata, and then XML Serialize it.
Brian Rudolph
Thanks Brian, but what I am doing is different. I just store some external program settings to load into the app. The examples might not be clear, but it's the user who can add more stuff to the xml.
Joan Venge
+1  A: 

Have you checked out the XmlSerializer class? That may be useful, and it can certainly handle parsing lists it generated. (Not sure if it's exactly what you want, though.)

NickAldwin
Thanks. Yeah, this is just for storing the settings themselves for the app.
Joan Venge
A: 

In your case you could just have

List<string> Fruits;

in your class somewhere which would serialize to

<Fruits>
   <string>Apple</string>
   <string>Orange</string>
</Fruits>

I believe.

For something more involved with nested lists of objects, you might want to declare a class Fruits as a List like so:

[Serializable]
public class Fruits: List<Fruit>
{ 
    // empty public constructor to make it serializable
    public Fruits()
    {
    }

    // ...
}

There are cases where you wouldn't be able to put, for example List<Flavors> directly into the Fruit class and have it serialize a list of lists (or was it an array of lists or a list of arrays? I forget---I know I had a problem with this); you would need another class Flavors : List<Flavors> and so forth.

Jared Updike
A: 

The only reason to use XML in the first place is so that you can use an XML parser to parse its content. This becomes staggeringly clear when you start working with the tools that make XML genuinely useful, like schemas and transforms (or XML serialization): any data structures that you embed in text content are unavailable to those tools.

Robert Rossney
+1  A: 

If you're looking to store application settings, then take a look at the types in the System.Configuration Namespace, or look into using Application Settings.

John Saunders