tags:

views:

101

answers:

7

I am new to dealing with XML and I have to store key/value pairs. Is there a preferred way of doing this? Here are a few possibilities I could come up with:

Way 1

<item key="k1" value="val1" />
<item key="k2" value="val2" />
<item key="k3" value="val3" />

Way 2

<item><key>k1</key><value>val1</value></item>
<item><key>k2</key><value>val2</value></item>
<item><key>k3</key><value>val3</value></item>

Way 3

<key name="k1">val1</key>
<key name="k2">val2</key>
<key name="k3">val3</key>

Thanks.

update: In the meantime I have found this: http://www.ibm.com/developerworks/xml/library/x-eleatt.html

A: 

The Way 3 is used by the 'java properties' files. Here is its DTD:

 <!ELEMENT properties ( comment?, entry* ) >
    <!ATTLIST properties version CDATA #FIXED "1.0">
    <!ELEMENT comment (#PCDATA) >
    <!ELEMENT entry (#PCDATA) >
    <!ATTLIST entry key CDATA #REQUIRED>
Pierre
A: 

XML is flexible. You can choose whatever you want. I would choose 3. I think 3 is most flexible.

prostynick
A: 

In the end I think it's a matter of preference and not best practices (unless somebody can give me an example why one is superior to the other). I prefer to use way 3 and way 1.

rslite
+1  A: 

The default way of saving XML files is Way 2, as a lot of XML files use that markup.

But Personally I prefer Way 1 for markup over the others.

It produces way smaller files in terms to readability and linecount, gives a good overview of the items contained in another, bigger element and you don't have to bother creating an end-element tag for each item used in the file (except the container items).

But at the ent of the day, it comes to what YOU prefer and are comfortable with.

Shaharyar
A: 
transmogrify
A: 

One more alternative, which strikes me as being more in the spirit of XML (assuming your keys are valid QNames, and your values don't include anything that would result in non-well-formed XML):

<k1>val1</k1>
<k2>val2</k2>
<k3>val3</k3>
NickFitz
A: 

As long as the keys are going to be valid XML names, and the values have a straightforward text representation, I'll do it like this:

<map key1="value1" key2="value2" key3="value3".../>

since attributes are, by definition, a mapping of names to values in which the order of the mapping is insignificant - just like a map/dictionary/hash table.

There are a ton of cases where you can't do it this way - if 123 is a valid key, for instance, or if the values (or keys) are serialized objects. Actually it's OK if the values are serialized objects, as long as you don't mind that they'll show up in the attribute values with all the markup escaped.

Robert Rossney