简体   繁体   中英

If a schema requires an attribute and I send it as an element, is it invalid?

A related node here was - XML Attributes vs Elements but that was more a design question.

My question is about validity.

If a schema requires

<record name="foo" description="bar" />

and I supply

<record>
  <name>foo</name>
  <description>bar</description>
</record>

Will the XML be considered invalid?

And vice versa: if elements were specified and I provide attributes, is it invalid?

Is there a reference in an XML spec documenting what an XML parser should do in this case, where the semantics is the same, but the literal XML structure differs?

If an XML schema says that is needs an element and you provide an attribute then that is invalid. The converse is the same. If you don't verify the XML, your code will still have problems because you will be looking for an attribute and it will not find the element.

Attributes and elements are in no way interchangeable. If the schema requires one, using the other is not valid, and the XML schema validation logic should reject it. Whether they are semantically identical is also highly questionable.

In XML, a schema is a strict contract: if you don't comply with it then the deal is over !

If the attributes were specified as elements, is the XML valid ?

Answer: it is invalid .

If elements were specified as attributes, is the XML valid ?

Answer: it is invalid .

What an XML parser should do in this case ?

Answer: fail on parsing for schema validity reasons.

An XML reader won't adapt to any mistake inside a source document. On this topic, the XML world is opposed to the HTML world. This strictness is a property of XML which allows it to be easy to parse, process and generate.

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