4

I created XML parsing logic that forces XML to be formatted like this:

<fooList>
    <fooObject value="SomeValue1" />
    <fooObject value="SomeValue2" />
</fooList>

And then I started to think that a more elegant way would be

<fooList>
    <fooObject>SomeValue1</fooObject>
    <fooObject>SomeValue2</fooObject>
</fooList>

Are there any recommendations or good practices regarding this? I already know about Element vs. Attribute question, please note that mine is different.

Danio
  • 141
  • 2
    To begin with, as an attribute [SomeValue1] now may have problems if it has &, or quotes, <> or newlines... Not that it cannot be solved, but you lost the flexibility of just using a CDATA item and dump whatever you want in there. – SJuan76 Sep 05 '14 at 15:11
  • @SJuan76 Not if your data can contain the substring ]]> (i.e. a CDATA section terminator). Properly escaping all output is the only robust option when creating XML or HTML files. Escaping the characters &'"<> really isn't that hard. – amon Sep 05 '14 at 15:21
  • @amon you can escape the ]]> substring by ending and restarting the section halfway through the string – ratchet freak Sep 05 '14 at 16:12
  • @DanPichelman I'd prefer it to go the other way. This one is a much better written question. Sure that one's closed, but a mod can reopen and insta-close as a duplicate. – Cole Tobin Sep 05 '14 at 16:31
  • @ColeJohnson I think you can flag the other as a duplicate of this one. – Dan Pichelman Sep 05 '14 at 17:30

2 Answers2

3

No, it is not bad practice.

In narrative text, it's a good idea to use text nodes for things the user will see (<title>Introduction</title>), and attributes for things the user won't see (<hr width="3pt"/>). In data-oriented XML, the decision is highly arbitrary, and neither way is right or wrong. Using elements is perhaps more extensible, since it allows you to introduce additional levels of structure in the future.

Michael Kay
  • 3,474
3

If there's other xml data in the same system, try to use a consistent approach.

If there's not other xml data (or you're defining all of it), use whatever is easiest to use in your tool chain.

Eben
  • 141