XML: attributes or children? [duplicate]

孤街浪徒 提交于 2019-12-02 02:55:10

问题


In XSD, SOAP and other XML conventions you'll often see things like:

<book>
 <title>Harry Potter</title>
 <author>J.K. Rowling</author>
</book>

Now I'm wondering, what happened to attributes? To me it makes more sense to write this as:

<book title="Harry Potter" author="J.K. Rowling" />

But apparently, for some reason, smarter people than me chose otherwise. Could someone explain why, and what attributes are for then?


回答1:


Some people consider the difference a matter of personal preference. There are a few guidlines out there you can follow.

W3Schools - XML Elements Vs. Attributes

IBM - Principles of XML Design




回答2:


There's no hard and fast rule. I tend to use attributes for metadata about the data contained in the elements. e.g

<book author="JK Rowling" published="September 2001">Harry Potter</book>

although usage/particular requirements will determine this more than anyrhing else.

Another issue is the subsequent processing. If you're using a SAX processor then this format will result in one method callback with the atteribute structure populated. Putting the data in multiple elements will result in the corresponding number of method calls (this may be an optimisation too far, but it may be worth considering depending on the quantity of data)



来源:https://stackoverflow.com/questions/825147/xml-attributes-or-children

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!