XML attribute vs XML element

前端 未结 20 2722
暖寄归人
暖寄归人 2020-11-22 01:34

At work we are being asked to create XML files to pass data to another offline application that will then create a second XML file to pass back in order to update some of ou

20条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 02:03

    There is no universal answer to this question (I was heavily involved in the creation of the W3C spec). XML can be used for many purposes - text-like documents, data and declarative code are three of the most common. I also use it a lot as a data model. There are aspects of these applications where attributes are more common and others where child elements are more natural. There are also features of various tools that make it easier or harder to use them.

    XHTML is one area where attributes have a natural use (e.g. in class='foo'). Attributes have no order and this may make it easier for some people to develop tools. OTOH attributes are harder to type without a schema. I also find namespaced attributes (foo:bar="zork") are often harder to manage in various toolsets. But have a look at some of the W3C languages to see the mixture that is common. SVG, XSLT, XSD, MathML are some examples of well-known languages and all have a rich supply of attributes and elements. Some languages even allow more-than-one-way to do it, e.g.

    ;
    

    or

    
      bar;
    ;
    

    Note that these are NOT equivalent syntactically and require explicit support in processing tools)

    My advice would be to have a look at common practice in the area closest to your application and also consider what toolsets you may wish to apply.

    Finally make sure that you differentiate namespaces from attributes. Some XML systems (e.g. Linq) represent namespaces as attributes in the API. IMO this is ugly and potentially confusing.

提交回复
热议问题