XML Tutorial/XML Schema/default

Материал из Web эксперт
Перейти к: навигация, поиск

Default and Fixed Values

In XML Schemas, you can declare default and fixed values for elements as well as attributes. 
When declaring default values for elements, you can specify only a text value. 
To specify a default value, simply include the default attribute with the desired value. 
<element name="last" type="string" default="Doe"/> 
<last></last> or <last/> then it would treat the element as: <last>Doe</last> 
If the element does not appear within the document or if the element already has content, 
then the default value is not used. 
When an element"s value can never change, simply include a fixedattribute with the fixed value. 
<element name="version" type="string" fixed="1.0"/>

You may not set both the default and fixed attributes at the same time

If the default attribute is set but the element is omitted, then the element"s value is set to the default value.
If the default attribute is set and the element does appear in the XML, its content is unrestricted (depending on the fixed attribute).

File: Schema.xsd
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  targetNamespace="http://www.wbex.ru" xmlns="http://www.wbex.ru"
  <xsd:element name="status" type="xsd:string" default="endangered" />
File: Data.xml
<?xml version="1.0"?> 
<status xmlns="http://www.wbex.ru">endangered</status>