开发者

Is it better to have information about an XML node as an attribute or a child node?

I prefer to have my XML documents structured in the following way:

<root>
   <node info1="blah" info2="blah" />
   <node info1="blah" info2="blah" />
</root>

Instead of:

<root>
   <node>
      <info1>blah</info1>
      <info2>blah</info2>
   <node>
   <node>
      <info1>blah</info1>
      <info2>blah</info2>
   <node开发者_运维问答>
</root>

I think this makes things easier to read and makes navigation simpler. Are there any reasons that the second example would be better? Is it same to assume my structure is better?

Obviously if there is a one to many relationship in the data I have no problem moving it to it's own child node.


I like the attributes in the interest of brevity and expressiveness.

I would go with the sub node in the following cases:

  • When I anticipate the sub node to have its own additional information. Ex: if info1 happens to be (or potentially can become) a structure rather than a simple type.
  • Let us say info1 is a SQL statement or a script or one of those things that require a lot of escape sequences. Then it is cumbersome to write that as an attribute. Far easier to make it a sub node so that you can benefit from the [!CDATA[ syntax.

Sometimes, in my configuration files I support both syntaxes so that the author of the configuration file can make the decision to use one of them as they deem appropriate.


The two types are slightly different in terms of the constraints that may be imposed by a DTD, and in terms of ordering for streaming (all attributes of a node are delivered before any of its child nodes).

Otherwise, you're right that they're interchangeable and the attribute syntax is more concise.


Two yet unmentioned differences:

  • accessing the xml using SAX attributes are ALWAYS delivered in one piece, while elements may be split
  • extensibility favours elements: the info1 and info2 already suggests, there may be more infos one day; this is much easier using elements
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜