Search code examples
xmlflags

XML and "flags"


What's the "proper" way to encode a numeric flags variable in XML?

I'm converting a program that dumps data between a couple of systems. Currently the dump is a tab-separated-values file (tabs shown as ⟿ here):

blah de blah ⟿ blargh ⟿ 176 ⟿ ...

One of the fields is a number representing a "flags" word in the source DB:

#define COURTEOUS     1             /* names changed to protect something */
#define KIND          2
#define FORGIVING     4
#define WITTY         8
#define OBSEQUIOUS   16
#define PURPLE       32
#define HAPPY        64
#define CLAIRVOYANT 128
#define WISE        256
      ...

It has been expressed that a number may not be the handiest way to transmit this information. My current thinking is running along these lines:

<things>
    <thing>
        <name>blah de blah</name>
        <owner>blargh</owner>
        <flags value='176'>
            <flag>OBSEQUIOUS</flag>
            <flag>PURPLE</flag>
            <flag>CLAIRVOYANT</flag>
        </flags>
            ...
    </thing>
        ...
</things>

Is this a sensible approach? Is there some sort of standard approach to this? Would this:

        <flags value='176'>
            <OBSEQUIOUS/>
            <PURPLE/>
            <CLAIRVOYANT/>
        </flags>

be an improvement?

Thanks!


Solution

  • I prefer the to use tags to represent structure rather than content, so my preference would be to use your first option

    <flag>OBSEQUIOUS</flag>
    <flag>PURPLE</flag>
    <flag>CLAIRVOYANT</flag>
    

    If you are using an XML schema, you can use an enumeration to validate that the values of your flag fields are within a predefined set. The schema then acts as documentation to the user of your XML format making the valid values explicit (if you do indeed know all the possible values at the time you are designing the schema.).

    <xs:simpleType name='Beatle' >
      <xs:restriction base='xs:string' >
        <xs:enumeration value='OBSEQUIOUS' />
        <xs:enumeration value='PURPLE' />
        <xs:enumeration value='CLAIRVOYANT' />
      </xs:restriction>
    </xs:simpleType>
    

    As others have commented, there is no good reason to store both the bitarray value and the flags themselves. In some circumstances you could store the bitarray value only, for example if the size of the XML file must be kept as small as possible, or for performance reasons. This would sacrifice readability and portability so should only be done if the trade off for performance is worth it.