Alex Rivera | Logout

XML Dom: storing key/value pairs

Asked 2009-10-09T12:05:14.390
21

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

Edit
Report

1 Answer

-1

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.

answered 2009-10-11T08:24:15.583

Your Answer