简体   繁体   中英

xml how to define data?

In the xml, which way is better when define data in content or in the attribute ? Thanks

<order id='' orderBy='' orderTime=''>
   .....
</order>

or

<order id=''>
  .....
  <orderBy>.. </orderBy>
  <orderTime>...</orderTime>
</order>

Depends what the data will be. If the data are just simple strings then the first one will be fine.

The second one is important to use if you need to in the future wrap in CDATA . So if the data is long or may contain html in the future then I suggest using the second form. If you look at twitter's XML feed , you will notice that they prefer using an element for almost all of their properties. Using elements give you flexibility in the future if you need to add more multiple elements of the same type.

Here is an article you should read that discusses this topic.

My advice is to perhaps keep your id in an attribute but the rest in an element.

In general, I prefer to use elements instead of attributes, as elements can later be expanded upon (the "extensible" part of XML). However, when you have a rather specific data type as with both of your examples here, you're probably best off keeping them as attributes - especially if orderTime is a standard XML dateTime type.

I would like to add one more point, if CDATA is not issue, then I prefer as attribute than Element. Order Id, date, count etc., should be attributes. Order Items should be Elements.

Generally speaking, you use an attribute if:

  • there is only one item (of that name) within the parent node

Otherwise, you use an element if:

  • there can be more than one item (of that name) within the node, or
  • the item is complex, ie, may contain attibutes or sub-elements itself

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM