最佳实践:XML 属性与 XML 元素 - 何时应使用元素,何时应使用属性? [英] Best practices: XML attribute vs XML element - When should I use elements and when should I use attributes?

查看:29
本文介绍了最佳实践:XML 属性与 XML 元素 - 何时应使用元素,何时应使用属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪种格式是此 XML 数据的正确格式,它们是等效的还是在两者之间进行权衡?

Which would be the correct format for this XML data, are they equivalent or are there trade offs between the two?

1.

<sitemap>
  <category name="Animals">
    <section title="Dogs">
      <page url="/pics/greatdane.jpg" title="Great Dane"/>
    </section>
  </category>
</sitemap>

2.

<sitemap>
  <page>
    <category>Animals</category>
    <section>Dogs</section>
    <title>Great Dane</title>
    <url>/pics/greatdane.jpg</url>    
  </page>
</sitemap>

我已经用我的样式表实现了第一个示例,它似乎工作正常,但我不确定正确的形式应该是什么.

I've implemented the first example with my style sheet and it seems to work fine, but I'm unsure what the correct form should be.

推荐答案

属性与元素的问题已经存在了十年的大部分时间,并且没有正确的答案.而是考虑差异,从中您应该能够决定使用哪个:

The issue of attributes vs elements has been around for the better part of a decade and there is no right answer. Instead consider the differences and from that you should be able to decide which to use:

  • 一个属性只能有一个实例,尽管您可以通过使用 DTD 或 XML Schema 的元素强制实现这一点;
  • 属性是无序的.元素不是;
  • 如果没有子级,属性会导致更简洁的语法.比较:

  • There can be only one instance of an attribute although you can enforce this with elements using DTD or XML Schema;
  • Attributes are unordered. Elements are not;
  • Attributes lead to a more concise syntax if there are no children. Compare:

<页面名称="站点地图"/>

<page name="Sitemap"/>

到:

<page>
  <name>Sitemap</name>
</page>

我知道我更喜欢哪一个;

I know which one I prefer;

  • 现在不是很重要,因为 DTD 在 XML Schema 上的使用不多(如果有的话),但我还是要添加它:DTD 允许属性的默认值(隐含),但元素没有这种机制;和
  • 元素作为元素,可以有自己的子元素和属性.属性显然不能.

所以,从你的例子来看,你最里面的 <page> 元素有一个 URL 属性(尽管出于某种原因它是一个图像——也许是一个预览图标?如果是这样,属性名称会产生误导).一个网页只有一个网址(通常),因此这是一个可以作为属性的好例子.

So, from your example, your innermost <page> element has a URL attribute (although it's an image for some reason--perhaps a preview icon? If so the attribute name is misleading). A webpage only has one URL (generally) so that'd be a good example of something that could be an attribute.

另一方面,如果您想在页面上列出图像,显然可能不止一个,因此您需要为此添加元素.

If on the other hand you wanted to list the images on the page, there could obviously be more than one so you'd need elements for that.

但最终,大多数时候没有正确或错误的答案,这主要是风格问题.

But, in the end, most of the time there's no right or wrong answer and it's largely a question of style.

这篇关于最佳实践:XML 属性与 XML 元素 - 何时应使用元素,何时应使用属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆