Joan Venge
Joan Venge

Reputation: 331530

How can I store multiple items in an XML file for easy parsing?

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>

Upvotes: 1

Views: 304

Answers (5)

John Saunders
John Saunders

Reputation: 161831

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.

Upvotes: 1

Robert Rossney
Robert Rossney

Reputation: 96920

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.

Upvotes: 0

Jared Updike
Jared Updike

Reputation: 7277

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.

Upvotes: 0

NickAldwin
NickAldwin

Reputation: 11754

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.)

Upvotes: 1

Randolpho
Randolpho

Reputation: 56448

<Fruits>
 <Fruit>Apple</Fruit>
 <Fruit>Orange</Fruit>
</Fruits>

Upvotes: 15

Related Questions