6 SVG Document Structure


Contents


 

6.1 Defining an SVG document fragment: the 'svg' element

6.1.1 Overview

An SVG document fragment consists of any number of SVG elements contained within an 'svg' element.

An SVG document fragment can range from an empty fragment (i.e., no content inside of the 'svg' element), to a very simple SVG document fragment containing a single SVG graphics element such as a 'rect', to a complex, deeply nested collection of container elements and graphics elements.

An SVG document fragment can stand by itself as a self-contained file or resource, in which case the SVG document fragment is an SVG document, or it can be embedded inline as a fragment within a parent XML document.

The following example shows simple SVG content embedded as a fragment within a parent XML document. Note the use of XML namespaces to indicate that the 'svg' and 'ellipse' elements belong to the SVG namespace:

<?xml version="1.0" standalone="yes"?>
<parent xmlns="http://someplace.org"
       xmlns:svg="http://www.w3.org/Graphics/SVG/SVG-19991203.dtd">
   <!-- parent stuff here -->
   <svg:svg width="5cm" height="8cm">
      <svg:ellipse rx="200" ry="130" />
   </svg:svg>
   <!-- ... -->
</parent>

Download this example

This example shows a slightly more complex (i.e., it contains multiple rectangles) stand-alone, self-contained SVG document:

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG December 1999//EN" 
  "http://www.w3.org/Graphics/SVG/SVG-19991203.dtd">
<svg width="4in" height="3in">
  <desc>Four separate rectangles
  </desc>
    <rect width="20" height="60"/>
    <rect width="30" height="70"/>
    <rect width="40" height="80"/>
    <rect width="50" height="90"/>
</svg>

Download this example

'svg' elements can appear in the middle of SVG content. This is the mechanism by which SVG document fragments can be embedded within other SVG document fragments.

Another use for 'svg' elements within the middle of SVG content is to establish a new viewport and alter the meaning of CSS unit specifiers. See Establishing a new viewport and Redefining the meaning of CSS unit specifiers.

6.1.2 The 'svg' element

<!ENTITY % svgExt "" >
<!ELEMENT svg (%descTitleDefs;,metadata?,
                  (path|text|rect|circle|ellipse|line|polyline|polygon|
                   use|image|svg|g|switch|a
                   %ceExt;%svgExt;)*) >
<!ATTLIST svg
  xmlns CDATA #FIXED 'http://www.w3.org/Graphics/SVG/SVG-19991203.dtd'
  id ID #IMPLIED
  xml:lang NMTOKEN #IMPLIED
  xml:space (default|preserve) #IMPLIED
  class NMTOKENS #IMPLIED
  style CDATA #IMPLIED
  %graphicsElementEvents;
  %documentEvents;
  system-required NMTOKEN #IMPLIED
  system-language CDATA #IMPLIED
  x CDATA #IMPLIED
  y CDATA #IMPLIED
  width CDATA #REQUIRED
  height CDATA #REQUIRED
  refX CDATA #IMPLIED
  refY CDATA #IMPLIED
  viewBox CDATA #IMPLIED
  preserveAspectRatio CDATA 'xMidYMid meet'
  enableZoomAndPanControls (true | false) "true" 
  contentScriptType CDATA #IMPLIED >

Attribute definitions:

xmlns [:prefix] = "resource-name"
Standard XML attribute for identifying an XML namespace. Refer to the "Namespaces in XML" Recommendation [XML-NS].
Animatable: no.
id = "name"
Standard XML attribute for assigning a unique name to an element. Refer to the the "Extensible Markup Language (XML) 1.0" Recommendation [XML10].
Animatable: no.
xml:lang = "languageID"
Standard XML attribute to specify the language (e.g., English) used in the contents and attribute values of particular elements. Refer to the "Extensible Markup Language (XML) 1.0" Recommendation [XML10].
Animatable: no.
xml:space = "{default | preserve}"
Standard XML attribute to specify whether white space is preserved in character data. The only possible values are default and preserve. Refer to the "Extensible Markup Language (XML) 1.0" Recommendation [XML10] and to the discussion white space handling in SVG.
Animatable: no.
x = "<coordinate>"
(Has no meaning or effect on outermost 'svg' elements.) The x-coordinate of one corner of the rectangular region into which an embedded 'svg' element is placed. The default x-coordinate is zero. See Coordinate Systems, Transformations and Units.
Animatable: yes.
y = "<coordinate>"
(Has no meaning or effect on outermost 'svg' elements.) The y-coordinate of one corner of the rectangular region into which an embedded 'svg' element is placed. The default y-coordinate is zero. See Coordinate Systems, Transformations and Units.
Animatable: yes.
width = "<length>"
For outermost 'svg' elements, the intrinsic width of the SVG document fragment, with length being any valid expression for a length in SVG. For embedded 'svg' elements, the width of the rectangular region into which the 'svg' element is placed.
Animatable: yes.
height = "<length>"
For outermost 'svg' elements, the intrinsic height of the SVG document fragment, with length being any valid expression for a length in SVG. For embedded 'svg' elements, the height of the rectangular region into which the 'svg' element is placed.
Animatable: yes.
refX = "<coordinate>"
When referenced in the context that requires a reference point (e.g., a motion path animation), the x-coordinate of the reference point.
Animatable: yes.
refY = "<coordinate>"
When referenced in the context that requires a reference point (e.g., a motion path animation), the y-coordinate of the reference point.
Animatable: yes.

Attributes defined elsewhere:
class, style, %graphicsElementEvents;, %documentEvents;, system-required, system-language, viewBox, preserveAspectRatio, enableZoomAndPanControls, contentScriptType.

 

6.2 Grouping and Naming Collections of Drawing Elements: the 'g' element

6.2.1 Overview

The 'g' element is the element for grouping and naming collections of drawing elements. If several drawing elements share similar attributes, they can be collected together using a 'g' element. For example:

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG December 1999//EN" 
  "http://www.w3.org/Graphics/SVG/SVG-19991203.dtd">
<svg width="4in" height="3in">
  <desc>Two groups, each of two rectangles
  </desc>
  <g style="fill:red">
    <rect x="100" y="100" width="100" height="100" />
    <rect x="300" y="100" width="100" height="100" />
  </g>
  <g style="fill:blue">
    <rect x="100" y="300" width="100" height="100" />
    <rect x="300" y="300" width="100" height="100" />
  </g>
</svg>

Download this example

A group of drawing elements, as well as individual objects, can be given a name. Named groups are needed for several purposes such as animation and re-usable objects. The following example organizes the drawing elements into two groups and assigns a name to each group:

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG December 1999//EN" 
  "http://www.w3.org/Graphics/SVG/SVG-19991203.dtd">
<svg width="4in" height="3in">
  <desc>Two named groups
  </desc>
  <g id="OBJECT1">
    <rect x="100" y="100" width="100" height="100" />
  </g>
  <g id="OBJECT2">
    <circle cx="150" cy="300" r="25" />
  </g>
</svg>

Download this example

A 'g' element can contain other 'g' elements nested within it, to an arbitrary depth. Thus, the following is valid SVG:

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG December 1999//EN" 
  "http://www.w3.org/Graphics/SVG/SVG-19991203.dtd">
<svg width="4in" height="3in">
  <desc>Groups can nest
  </desc>
  <g>
     <g>
       <g>
       </g>
     </g>
   </g>
</svg>

Download this example

Any drawing element that is not contained within a 'g' is treated (at least conceptually) as if it were in its own group.

6.2.2 The 'g' element

<!ENTITY % gExt "" >
<!ELEMENT g (%descTitleDefs;,
                  (path|text|rect|circle|ellipse|line|polyline|polygon|
                   use|image|svg|g|switch|a|
                   animate|set|animateMotion|animateColor|animateTransform
                   %ceExt;%gExt;)*) >
<!ATTLIST g
  id ID #IMPLIED
  xml:lang NMTOKEN #IMPLIED
  xml:space (default|preserve) #IMPLIED
  class NMTOKENS #IMPLIED
  style CDATA #IMPLIED
  transform CDATA #IMPLIED
  %graphicsElementEvents;
  system-required NMTOKEN #IMPLIED 
  system-language CDATA #IMPLIED >

Attributes defined elsewhere:
id, xml:lang, xml:space, class, style, transform, %graphicsElementEvents;, system-required, system-language.

6.3 References and the 'defs' element

6.3.1 Overview

SVG makes extensive use of URI references [URI] to other objects. For example, to fill a rectangle with a linear gradient, you first define a 'linearGradient' element and give it an ID, as in:

<linearGradient id="MyGradient">...</linearGradient>

You then reference the linear gradient as the value of the 'fill' property for the rectangle, as in:

<rect style="fill:url(#MyGradient)"/>

In SVG, the following facilities allow URI references:

URI references are defined in either of the following forms:

<URI-reference> = [ <absoluteURI> | <relativeURI> ] [ "#" <elementID> ]    -or-
<URI-reference> = [ <absoluteURI> | <relativeURI> ] [ "#xptr(id(" <elementID> "))" ]

where <elementID> is the ID of the referenced element.

(Note that the two forms above (i.e., #<elementID> and #xptr(id(<elementID>))) are formulated in syntaxes compatible with "XML Pointer Language (XPointer)" [XPTR]. These two formulations of URI references are the only XPointer formulations that are required in SVG 1.0 user agents.)

SVG supports two types of URI references:

The following rules apply to the processing of URI references:

Unless a given attribute or property has defined fallback behavior in case a reference cannot be resolved, invalid references are treated as errors (see Error Processing). For example, if there is no element with ID "BogusReference" in the current document, then fill="url(#BogusReference)" would represent an invalid reference and would be an error.

6.3.2 URI reference attributes


 
<!ENTITY % xlinkRefAttrs
  xmlns:xlink CDATA #FIXED "http://www.w3.org/XML/XLink/0.9"
  xlink:type (simple|extended|locator|arc) #FIXED "simple" 
  xlink:role CDATA #IMPLIED
  xlink:title CDATA #IMPLIED
  xlink:show (new|embed|replace) #FIXED 'embed'
  xlink:actuate (user|auto) #FIXED 'auto'
>

  xlink:href CDATA #REQUIRED
xmlns [:prefix] = "resource-name"
Standard XML attribute for identifying an XML namespace. This attribute makes the XLink [XLink] namespace available to the current element. Refer to the "Namespaces in XML" Recommendation [XML-NS].
Animatable: no.
xlink:type = 'simple'
Identifies the type of XLink being used. For hyperlinks in SVG, only simple links are available. Refer to the "XML Linking Language (XLink)" [XLink].
Animatable: no.
xlink:role = '<string>'
A generic string used to describe the function of the link's content. Refer to the "XML Linking Language (XLink)" [XLink].
Animatable: no.
xlink:title = '<string>'
Human-readable text describing the link. Refer to the "XML Linking Language (XLink)" [XLink].
Animatable: no.
xlink:show = 'embed'
Indicates that upon activation of the link the contents of the referenced object are incorporated appropriately into the current SVG document fragment. Refer to the "XML Linking Language (XLink)" [XLink].
Animatable: no.
xlink:actuate = 'auto'
Indicates that the contents of the referenced object are incorporated into the current document automatically (i.e., without user action). Refer to the "XML Linking Language (XLink)" [XLink].
Animatable: no.
xlink:href = "<uri>"
The location of the referenced object, expressed as a URI reference. Each element in SVG which has an xlink:href attribute will describe the particular usage rules relevant to that element. Refer to the "XML Linking Language (XLink)" [XLink].
Animatable: yes.

6.3.3 The 'defs' element

The 'defs' element is used to identify those objects which will be referenced by other objects later in the document. It is a requirement that all referenced objects be defined within a 'defs' element. (See References and the 'defs' element.)

The child elements within a 'defs' element are not drawn.

<!ENTITY % defsExt "" >
<!ELEMENT defs (script|style|symbol|marker|clipPath|mask|
                linearGradient|radialGradient|pattern|filter|cursor|font|
                animate|set|animateMotion|animateColor|animateTransform|
                path|text|rect|circle|ellipse|line|polyline|polygon|
                use|image|svg|g|view|switch|altGlyphDef
                %ceExt;%defsExt;)* >
<!ATTLIST defs
  id ID #IMPLIED
  xml:lang NMTOKEN #IMPLIED
  xml:space (default|preserve) #IMPLIED
  class NMTOKENS #IMPLIED
  style CDATA #IMPLIED >

Attributes defined elsewhere:
id, xml:lang, xml:space, class, style.

To provide some SVG user agents with an opportunity to implement efficient implementations in streaming environments, creators of SVG content are encouraged to place all elements which are targets of local URI references within a 'defs' element which is a direct child of one of the ancestors of the referencing element. For example:

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG December 1999//EN" "http://www.w3.org/Graphics/SVG/SVG-19991203.dtd">
<svg width="4in" height="3in">
  <desc>Local URI references within ancestor's 'defs' element.</desc>
  <defs>
    <linearGradient id="Gradient01">
      <stop offset="30%" style="color:#39F"/>
    </linearGradient>
  </defs>
  <g>
    <g>
      <rect x="0%" y="0%" width="100%" height="100%" 
            style="fill:url(#Gradient01)" />
    </g>
  </g>
</svg>

Download this example

In the document above, the linear gradient is defined within a 'defs' element which is the direct child of the 'svg' element, which in turn is an ancestor of the 'rect' element which references the linear gradient. Thus, the above document conforms to the guideline.

6.4 The 'desc' and 'title' elements

Each container element or graphics element in an SVG drawing can supply a 'desc' and/or a 'title' description string where the description is text-only. For visual presentation, the SVG default stylesheet has 'display:none' for 'desc' and 'title' elements. Thus, they are not drawn as text in the graphic. User agents may, for example, display the 'title' element as a tooltip, as the pointing device moves over particular elements. Alternate presentations are possible, both visual and aural, which display the 'desc' and 'title' elements but do not display 'path' elements or other graphics elements. This is readilly achieved by using a different (perhaps user) stylesheet. For deep hierarchies, and for following 'use' element references, it is sometimes desirable to allow the user to control how deep they drill down into descriptive text.

The following is an example. In typical operation, the SVG user agent would not render the 'desc' and 'title' elements but would render the remaining contents of the 'g' element.

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg SYSTEM "http://www.w3.org/Graphics/SVG/SVG-19991203.dtd">
<svg width="4in" height="3in">
<g>
  <title>
    Company sales by region
  </title>
  <desc>
    This is a bar chart which shows 
    company sales by region.
  </desc>
  <!-- Bar chart defined as vector data -->
</g>
</svg>

Download this example

Description and title elements can contain marked-up text from other namespaces. Here is an example:

<?xml version="1.0" standalone="yes"?>
<svg width="4in" height="3in" 
 xmlns="http://www.w3.org/Graphics/SVG/SVG-19991203.dtd">
   <desc xmlns:mydoc="http://foo.org/mydoc">
      <mydoc:title>This is an example SVG file</mydoc:title>
      <mydoc:para>The global description uses markup from the 
        <mydoc:emph>mydoc</mydoc:emph> namespace.</mydoc:para>
   </desc>
   <g>
   <!-- the picture goes here -->
   </g>
</svg>

Download this example


6.5 The 'symbol' element

The 'symbol' element is used to define graphical objects which are meant for any of the following uses:

Closely related to the 'symbol' element are the 'marker' and 'pattern' elements.
 
<!ENTITY % symbolExt "" >
<!ELEMENT symbol (%descTitleDefs;,
                  (path|text|rect|circle|ellipse|line|polyline|polygon|
                   use|image|svg|g|switch|a
                   %ceExt;%symbolExt;)*) >
<!ATTLIST symbol
  id ID #IMPLIED
  xml:lang NMTOKEN #IMPLIED
  xml:space (default|preserve) #IMPLIED
  class NMTOKENS #IMPLIED
  style CDATA #IMPLIED
  refX CDATA #IMPLIED
  refY CDATA #IMPLIED
  viewBox CDATA #IMPLIED
  preserveAspectRatio CDATA 'xMidYMid meet' >


Attributes defined elsewhere:
id, xml:lang, xml:space, class, style, refX, refY, viewBox, preserveAspectRatio.

6.6 The 'use' element

Any 'svg', 'symbol', 'g', or graphics element that is a child of a 'defs' element and has been assigned an ID is potentially a template object that can be re-used (i.e., "instanced") anywhere in the SVG document via a 'use' element. The 'use' element references another element and indicates that the graphical contents of that element is included/drawn at that given point in the document.

The 'use' element can reference either:

Unlike 'image', the 'use' element cannot reference entire files.

In the example below, the first 'g' element has inline content. After this comes a 'use' element whose href value indicates which graphics element is included/rendered at that point in the document. Finally, the second 'g' element has both inline and referenced content. In this case, the referenced content will draw first, followed by the inline content.

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG December 1999//EN" 
  "http://www.w3.org/Graphics/SVG/SVG-19991203.dtd">
<svg width="4in" height="3in">
  <defs>
    <symbol id="TemplateObject01">
      <!-- symbol definition here -->
    </symbol>
  </defs>

  <desc>Examples of inline and referenced content
  </desc>
  
  <!-- <g> with inline content -->
  <g>
    <!-- Inline content goes here -->
  </g>

  <!-- referenced content -->
  <use xlink:href="#TemplateObject01" />

  <!-- <g> with both referenced and inline content -->
  <g>
    <use xlink:href="#TemplateObject01" />
    <!-- Inline content goes here -->
  </g>
</svg>

Download this example

The 'use' element has optional attributes x, y, width and height which are used to map the graphical contents of the referenced element onto a rectangular region within the current coordinate system.

The effect of a 'use' element is as if the contents of the referenced element were deeply cloned into a separate non-exposed DOM tree which had the 'use' element as its parent and all of the 'use' element's ancestors as its higher-level ancestors. Because the cloned DOM tree is non-exposed, the SVG Document Object Model (DOM) only contains the 'use' element and its attributes. The SVG DOM does not show the referenced element's contents as children of 'use' element.

Property inheritance, however, works as if the referenced element had been textually included as a deeply cloned child of the 'use' element. The referenced element inherits properties from the 'use' element and the 'use' element's ancestors. An instance of a referenced element does not inherit properties from its original parents.

The following example illustrates property inheritance with the 'use' element:

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG December 1999//EN" 
  "http://www.w3.org/Graphics/SVG/SVG-19991203.dtd">
<svg width="4in" height="3in">
  <defs style="stroke:green">
    <!-- Note that parent's stroke:green will have no effect below -->
    <circle id="TemplateObject02" cx="50" cy="50" r="30" style="fill:red" />
  </defs>

  <desc>Examples of <use> property inheritance
  </desc>
  
  <g style="fill:yellow;stroke:blue" >
    <!-- Draws a circle with fill:red and stroke:blue. -->
    <!-- Note that the referenced element specifies fill:red,
         which takes precedence over the inherited fill:yellow. -->
    <use xlink:href="#TemplateObject02" />
  </g>
</svg>

Download this example

In the example above, property inheritance for 'use' element shown above is as if the 'use' element were replaced by a container object whose contents are the referenced element:

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG December 1999//EN" 
  "http://www.w3.org/Graphics/SVG/SVG-19991203.dtd">
<svg width="4in" height="3in">
  <defs style="stroke:green">
    <!-- Note that parent's stroke:green will have no effect below -->
    <circle id="TemplateObject02" cx="50" cy="50" r="30" style="fill:red" />
  </defs>

  <desc>Examples of <use> property inheritance
  </desc>
  
  <g style="fill:yellow;stroke:blue" >
    <!-- Draws a circle with fill:red and stroke:blue. -->
    <!-- Note that the referenced element specifies fill:red,
         which takes precedence over the inherited fill:yellow. -->
    <g>
      <circle cx="50" cy="50" r="30" style="fill:red" />
    </g>
  </g>
</svg>

Download this example


 
<!ENTITY % useExt "" >
<!ELEMENT use (%descTitle;,(animate|set|animateMotion|animateColor|animateTransform
                   %geExt;%useExt;)*) >
<!ATTLIST use
  id ID #IMPLIED
  xml:lang NMTOKEN #IMPLIED
  xml:space (default|preserve) #IMPLIED
  class NMTOKENS #IMPLIED
  style CDATA #IMPLIED
  transform CDATA #IMPLIED
  %graphicsElementEvents;
  system-required NMTOKEN #IMPLIED
  system-language CDATA #IMPLIED
  x CDATA #IMPLIED
  y CDATA #IMPLIED
  width CDATA #IMPLIED
  height CDATA #IMPLIED
  %xlinkRefAttrs;
  xlink:href CDATA #REQUIRED >

Attribute definitions:

x = "<coordinate>"
The x coordinate of one corner of the rectangular region into which the referenced element is placed. The default x coordinate is zero. See Coordinate Systems, Transformations and Units.
Animatable: yes.
y = "<coordinate>"
The y coordinate of one corner of the rectangular region into which the referenced element is placed. The default y coordinate is zero. See Coordinate Systems, Transformations and Units.
Animatable: yes.
width = "<length>"
The width of the rectangular region into which the referenced element is placed.
Animatable: yes.
height = "<length>"
The height of the rectangular region into which the referenced element is placed.
Animatable: yes.
xlink:href = "<uri>"
A URI reference to an element/fragment within an SVG document.
Animatable: yes.

Attributes defined elsewhere:
id, xml:lang, xml:space, class, style, transform, %graphicsElementEvents;, system-required, system-language, %xlinkAttrs;.

6.7 The 'image' element

The 'image' element indicates that the contents of a complete file are to be rendered into a given rectangle within the current user coordinate system. The 'image' element can refer to raster image files such as PNG or JPEG or to files with MIME type of "image/svg". Conforming SVG viewers need to support at least PNG, JPEG and SVG format files.

The resource referenced by the 'image' element represents a separate document which generates its own parse tree and document object model (if the resource is XML). Thus, there is no inheritance of properties into the image.

Unlike 'use', the 'image' element cannot reference elements within an SVG file.
 
<!ENTITY % imageExt "" >
<!ELEMENT image (%descTitle;,(animate|set|animateMotion|animateColor|animateTransform
                   %geExt;%imageExt;)*) >
<!ATTLIST image
  id ID #IMPLIED
  xml:lang NMTOKEN #IMPLIED
  xml:space (default|preserve) #IMPLIED
  class NMTOKENS #IMPLIED
  style CDATA #IMPLIED
  transform CDATA #IMPLIED
  %graphicsElementEvents;
  system-required NMTOKEN #IMPLIED
  system-language CDATA #IMPLIED
  x CDATA #IMPLIED
  y CDATA #IMPLIED
  width CDATA #REQUIRED
  height CDATA #REQUIRED
  %xlinkRefAttrs;
  xlink:href CDATA #REQUIRED >

Attribute definitions:

x = "<coordinate>"
The x coordinate of one corner of the rectangular region into which the referenced document is placed. The default x coordinate is zero. See Coordinate Systems, Transformations and Units.
Animatable: yes.
y = "<coordinate>"
The y coordinate of one corner of the rectangular region into which the referenced document is placed. The default y coordinate is zero. See Coordinate Systems, Transformations and Units.
Animatable: yes.
width = "<length>"
The width of the rectangular region into which the referenced document is placed.
Animatable: yes.
height = "<length>"
The height of the rectangular region into which the referenced document is placed.
Animatable: yes.
xlink:href = "<uri>"
A URI reference.
Animatable: yes.

Attributes defined elsewhere:
id, xml:lang, xml:space, class, style, transform, %graphicsElementEvents;, system-required, system-language, %xlinkAttrs;.

A valid example:

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG December 1999//EN" 
  "http://www.w3.org/Graphics/SVG/SVG-19991203.dtd">
<svg width="4in" height="3in">
  <desc>This graphic links to an external image
  </desc>
  <image x="200" y="200" width"100px" height="100px"
         xlink:href="myimage.png">
    <title>My image</title>
  </image>
</svg>

Download this example

A well-formed example:

<?xml version="1.0" standalone="yes"?>
<svg width="4in" height="3in"
 xmlns='http://www.w3.org/Graphics/SVG/SVG-19991203.dtd'>
  <desc>This links to an external image
  </desc>
  <image x="200" y="200" width"100px" height="100px"
         xlink:type="simple" xlink:show="embed" xlink:actuate="auto" 
         xlink:href="myimage.png">
    <title>My image</title>
  </image>
</svg>

Download this example


6.8 Conditional processing


6.8.1 Conditional processing overview

SVG contains a 'switch' element along with attributes system-required and system-language to provide an ability to specify alternate viewing depending on the capabilities of a given user agent or the user's language. These features operate with the same semantics as the corresponding features within the SMIL 1.0 Recommendation [SMIL1].

Attributes system-required and system-language act as tests and return either true or false results. The 'switch' renders the first of its children for which both attributes test true.


6.8.2 The 'switch' element

The 'switch' element evaluates the system-required and system-language attributes on its direct child elements in order, and then processes and renders the first child for which these two attributes evaluate to true. All others will be bypassed and therefore not rendered. If the child element is a container element such as a 'g', then the entire subtree is either processed/rendered or bypassed/not rendered.


 
<!ENTITY % switchExt "" >
<!ELEMENT switch (%descTitleDefs;,
                  (path|text|rect|circle|ellipse|line|polyline|polygon|
                   use|image|svg|g|switch|a|foreignObject|
                   animate|set|animateMotion|animateColor|animateTransform
                   %ceExt;%switchExt;)*) >
<!ATTLIST switch
  id ID #IMPLIED
  xml:lang NMTOKEN #IMPLIED
  xml:space (default|preserve) #IMPLIED
  class NMTOKENS #IMPLIED
  style CDATA #IMPLIED
  transform CDATA #IMPLIED
  %graphicsElementEvents;
  system-required NMTOKEN #IMPLIED 
  system-language CDATA #IMPLIED >


Attributes defined elsewhere:
id, xml:lang, xml:space, class, style, transform, %graphicsElementEvents;, system-required, system-language.

For more information and an example, see Embedding foreign object types.

6.8.3 The system-required attribute

Definition of system-required:

system-required = list-of-features
The value is a comma-separated list of feature strings. Determines whether all of the named features are supported by the user agent. If one of the given features is not supported, then the current element and its children are processed; otherwise, the current element and its children are skipped and thus will not be rendered and cannot be referenced by another element.
Animatable: no.

The following are the feature strings for the system-required attribute. These same feature strings apply to the hasFeature method call that is part of the SVG DOM's support for the DOMImplementation interface defined in [DOM2-CORE] (see Feature strings for the hasFeature method call).

If the attribute is not present, then its implicit return value is "true". If a null string or empty string value is given to attribute system-required, the attribute returns "false".

system-required is often used in conjunction with the 'switch' element. If the system-required is used in other situations, then it represented a simple switch on the given element whether to render the element or not.


6.8.4 The system-language attribute

The attribute value is a comma-separated list of language names as defined in [RFC1766].

Evaluates to "true" if one of the languages indicated by user preferences exactly equals one of the languages given in the value of this parameter, or if one of the languages indicated by user preferences exactly equals a prefix of one of the languages given in the value of this parameter such that the first tag character following the prefix is "-". Evaluates to "false" otherwise.

Further description of the system-language attribute can be found at [SMIL10-SYSLANG].

If the attribute is not present, then its implicit return value is "true". If a null string or empty string value is given to attribute system-required, the attribute returns "false".


6.9 DOM interfaces


6.9.1 Overview

This section describes the SVG-specific DOM interfaces that correspond to the topics described in this chapter.


6.9.2 Interface SVGDocument

When an 'svg' element is embedded inline as a component of a document from another namespace, such as when an 'svg' element is embedded inline within an XHTML document [XHTML10], then an SVGDocument object will not exist; instead, the root object in the document object hierarchy will be a Document object of a different type, such as an HTMLDocument object.

However, an SVGDocument object will indeed exist when the root element of the XML document hierarchy is an 'svg' element, such as when viewing a standalone SVG file (i.e., a file with MIME type "image/svg"). In this case, the SVGDocument object will be the the root object of the document object model hierarchy.

In the case where an SVG document is embedded by reference, such as when an XHTML document has an 'object' element whose href attribute references an SVG document (i.e., a document whose MIME type is "image/svg" and whose root element is thus an 'svg' element), there will exist two distinct DOM hierarchies. The first DOM hierarchy will be for the referencing document (e.g., an XHTML document). The second DOM hierarchy will be for the referenced SVG document. In this second DOM hierarchy, the root object of the document object model hierarchy is an SVGDocument object.

The SVGDocument interface contains a similar list of attributes and methods to the HTMLDocument interface described in Document Object Model (HTML) Level 1 chapter of the [DOM1] specification.


IDL Definition
interface SVGDocument : Document {
         attribute  DOMString            title;
readonly attribute  DOMString            referrer;
readonly attribute  DOMString            domain;
readonly attribute  DOMString            URL;

       attribute SVGSVGElement         rootElement;
Element                   getElementById(in DOMString elementId);

};

Attributes
title
The title of a document as specified by the title sub-element of the 'svg' root element (i.e., <svg><title>Here is the title</title>...</svg>)
referrer
Returns the URI of the page that linked to this page. The value is an empty string if the user navigated to the page directly (not through a link, but, for example, via a bookmark).
domain
The domain name of the server that served the document, or a null string if the server cannot be identified by a domain name.
URL
The complete URI of the document.
Methods
getElementById
Returns the Element whose id is given by elementId. If no such element exists, returns null. Behavior is not defined if more than one element has this id.
Parameters
elementId

The unique id value for an element.

Return Value
The matching element.

This method raises no exceptions.

6.9.3 The getSVGDocument method

In the case where an SVG document is embedded by reference, such as when an XHTML document has an 'object' element whose href (or equivalent) attribute references an SVG document (i.e., a document whose MIME type is "image/svg" and whose root element is thus an 'svg' element), the SVG user agent is required to provide getSVGDocument method for the element which references the SVG document (e.g., the HTML 'object' or comparable referencing elements).

Methods
getSVGDocument

Returns the SVGDocument object for the referenced SVG document.

No Parameters

Return Value

SVGDocument The SVGDocument object for the referenced SVG document.

Exceptions

DOMException NO_SVG_DOCUMENT: No SVGDocument object is available.

6.9.4 Interface SVGElement

All of the SVG DOM interfaces that correspond directly to elements in the SVG language (e.g., the SVGPathElement interface corresponds directly to the 'path' element in the language) are derivative from base class SVGElement.


IDL Definition
interface SVGElement : Element {
  attribute DOMString id;
  attribute DOMString lang;
  attribute DOMString space;
  readonly attribute  SVGSVGElement ownerSVGElement;
  readonly attribute  SVGElement viewportElement;
};

Attributes
id
The value of the id attribute on the given element.
lang
The value of the xml:lang attribute on the given element.
lang
The value of the xml:space attribute on the given element.
ownerSVGElement
The nearest ancestor 'svg' element. Null if this is the given element is the outermost 'svg' element.
viewportElement
The element which established the current viewport. Often, the nearest ancestor 'svg' element. Null if this is the given element is the outermost 'svg' element.

6.9.5 Interface SVGStyledElement

Interface SVGStyledElement is the base class for elements which can be styled but not transformed (i.e., elements which have a style attribute but not a transform attribute).


IDL Definition
interface SVGStyledElement : SVGElement {
  readonly attribute CSSStyleDeclaration  style;
           attribute DOMString            className;
};

Attributes
style
The value of the style attribute on the given element.
className
The value of the class attribute on the given element.

6.9.6 Interface SVGTransformedElement

Interface SVGTransformedElement is the base class for elements which can be transformed but not styled (i.e., elements which have a transform attribute but not a style attribute).


IDL Definition
interface SVGTransformedElement : SVGElement {
  readonly attribute  SVGElement       nearestViewportElement;
  readonly attribute  SVGElement       farthestViewportElement;
           attribute  SVGTransformList transform;

  SVGRect      getBBox();
  SVGMatrix    getCTM(); // returns CTM (userspace to [nearest 'svg'] viewport transform matrix)
  SVGMatrix    getTransformToElement(in SVGTransformedElement element)
                    raises(SVGException);
                    // returns transform matrix which maps coordinates from
                    // current user space to the user space of "element"
  SVGMatrix    getScreenCTM(); // returns CTM (userspace to screen units transform matrix)
};

Attributes
nearestViewportElement
The element which established the current viewport. Often, the nearest ancestor 'svg' element. Null if this is the given element is the outermost 'svg' element.
farthestViewportElement
The farthest ancestor 'svg' element. Null if this is the given element is the outermost 'svg' element.
transform
The value of the transform attribute on the given element.
Methods
getBBox
Returns the tight bounding box in current user space (i.e., after application of the transform attribute) on the geometry of all contained graphics elements, exclusive of stroke-width and filter effects.
No Parameters
Return Value
The bounding box.
Exceptions
SVGException SVG_NO_GRAPHICS_ELEMENTS: There are no graphics elements on which to perform the given action.
getCTM
Returns the transformation matrix from current user units (i.e., after application of the transform attribute) to the viewport coordinate system for the nearestViewportElement
No Parameters
Return Value
The transformation matrix.
No Exceptions
getTransformToElement
Returns the transformation matrix from the user coordinate system on the current element (after application of the transform attribute) to the user coordinate system on element (after application of its transform attribute)
Parameters
element
The target element.
Return Value
The transformation matrix.
No Exceptions
getScreenCTM
Returns the transformation matrix from current user units (i.e., after application of the transform attribute) to the parent user agent's notice of a "pixel". For display devices, ideally this represents a physical screen pixel. For other devices or environments where physical pixel sizes are not know, then an algorithm similar to the CSS2 definition of a "pixel" can be used instead.
No Parameters
Return Value
The transformation matrix.
No Exceptions

6.9.7 Interface SVGStyledAndTransformedElement

Interface SVGStyledAndTransformedElement is the base class for elements which can be both styled and transformed (i.e., elements which have both style and transform attributes).


IDL Definition
interface SVGStyledAndTransformedElement : SVGElement {
  readonly attribute CSSStyleDeclaration  style;
           attribute DOMString            className;

  readonly attribute  SVGElement       viewportElement; // element that established current viewport
           attribute  SVGTransformList transform;

  SVGRect      getBBox(); // tight bounding box on geometry of all contained 
                          // graphics elements, in userspace.
                          // Doesn't take into account stroke-width or filter effects, for example

  SVGMatrix    getNearestCTM(); // returns CTM (userspace to [nearest 'svg'] viewport transform matrix)
  SVGMatrix    getNearestCTMInverse()
               raises(SVGException); // returns inverse matrix (SVG_MATRIX_NOT_INVERTABLE)
  SVGMatrix    getFurthestCTM(); // returns CTM (userspace to [outermost 'svg'] viewport transform matrix)
  SVGMatrix    getFurthestCTMInverse()
               raises(SVGException); // returns inverse matrix (SVG_MATRIX_NOT_INVERTABLE)
  SVGMatrix    getScreenCTM(); // returns CTM (userspace to screen units transform matrix)
  SVGMatrix    getScreenCTMInverse()
               raises(SVGException); // returns inverse matrix (SVG_MATRIX_NOT_INVERTABLE)
};


6.9.8 Interface SVGSVGElement

A key interface definition is the SVGSVGElement interface, which is the interface that corresponds to the 'svg' element. This interface contains various miscellaneous commonly-used utility methods, such as matrix operations and the ability to control the time of redraw on visual rendering devices.


IDL Definition
interface SVGSVGElement : SVGStyledElement {

  // Viewport definition in coordinate system of object
  // containing this 'svg' element.
  // (See coords.html for discussion of containing parent.
  // Values are unitless values in parent's coordinate system.
  // If parent uses CSS layout, then values represent CSS pixels.)
  readonly attribute SVGRect viewport;

  // Size of a CSS "pixel", using the CSS2 definition of a pixel,
  // which represents a unit somewhere in the range of 70dpi to 120dpi,
  // and, on systems that support this, might actually match the 
  // characteristics of the target medium. On systems where it is 
  // impossible to know the size of a pixel, a suitable default 
  // pixel size is provided.
  readonly attribute float CSSPixelToMillimeterX;
  readonly attribute float CSSPixelToMillimeterY;

  // Size of a screen "pixel", which is the unit of size
  // returned to UI event handlers by the level 2 DOM.
  // (Again, various caveats about reliability of these values...)
  readonly attribute float ScreenPixelToMillimeterX;
  readonly attribute float ScreenPixelToMillimeterY;

  // If most recent user action was hyperlink into document 
  // using SVGViewSpec, then this is true and the
  // "currentView" object overrides the standard viewing
  // attributes on 'svg' element.
  // Otherwise, if the user more recently did a "Normal size", then the
  // boolean becomes false, and the attributes on the 'svg' element
  // are active, not currentView.
  attribute boolean useCurrentView;
  readonly attribute SVGViewSpec currentView;

  // Corresponds to the various viewing attributes on the 'svg' element.
  // Active only if 'useCurrentView' is false.
  attribute SVGRect viewBox;
  attribute SVGPreserveAspectRatio preserveAspectRatio;
  attribute boolean enableZoomAndPanControls;

  // Information about the current zoom and pan factors
  // relative to the base view (i.e., either currentView
  // or viewBox).
  // These attributes are equivalent to the 2x3 matrix
  // [a b c d e f] = [currentScale 0 0 currentScale currentTranslate.x currentTranslate.y]
  attribute float currentScale;
  attribute SVGPoint currentTranslate;


  // XML attributes on the 'svg' element.
  attribute SVGLength x;
  attribute SVGLength y;
  attribute SVGLength width;
  attribute SVGLength height;
  attribute SVGLength refX;
  attribute SVGLength refY;

  // Methods to eliminate flicker in scripted animations.
  unsigned long suspendRedraw(in unsigned long max_wait_milliseconds);
  void          unsuspendRedraw(in unsigned long suspend_handle_id)
                                 raises(DOMException);
  void          unsuspendRedrawAll();
  void          forceRedraw();


  // Methods to manage running animations.
  void          pauseAnimations()
                                 raises(DOMException);
  void          unpauseAnimations()
                                 raises(DOMException);
  boolean       animationsPaused();
  float         getDocumentBeginTime()
                                 raises(DOMException);
  float         getCurrentTime()
                                 raises(DOMException);
  void          setCurrentTime(in float seconds)
                                 raises(DOMException);


  void          deSelectAll(); // Unselects any text strings that are currently selected. 

  // Methods to create unattached standard object types.
  // Upon creation, these object types are unattached to
  // the document, but they can be assigned to document
  // attributes of the same type. For example:
  //    // Create a default SVGLength (zero user units).
  //    SVGLength myLength = createSVGLength();
  //    // Set the length to 2.3cm
  //    myLength.newValueSpecifiedUnits(myLength.kSVG_LENGTHTYPE_CM, 2.3);
  //    // Change the width of a rectangle to 2.3cm.
  //    myRect.width = myLength;
  SVGNumber              createSVGNumber();     // Returns unattached number 0
  SVGLength              createSVGLength();     // Returns unattached length of 0 user units
  SVGLengthList          createSVGLengthList(); // Returns unattached empty list
  SVGAngle               createSVGAngle();      // Returns unattached angle of 0 degrees
  SVGPoint               createSVGPoint();      // Returns unattached point (0,0) in user units
  SVGPointList           createSVGPointList();  // Returns unattached empty list of points
  SVGMatrix              createSVGMatrix();     // Returns unattached identity matrix. (e,f)=(0,0) in user units
  SVGPreserveAspectRatio createSVGPreserveAspectRatio();  // Returns unattached object with values 'none' and 'meet'
  SVGRect                createSVGRect();       // Returns unattached rect x=y=width=height=0 in user units.
  SVGTransformList       createSVGTransformList(); // Returns unattached SVGTransform spec with identity matrix
  SVGTransformList       createSVGTransformListFromMatrix(in SVGMatrix matrix); // Returns unattached SVGTransform spec
  SVGTransform           createSVGTransform();     // Returns unattached identity matrix
  SVGTransform           createSVGTransformFromMatrix(in SVGMatrix matrix); // Returns unattached transform
  SVGLengthList          createSVGTransformList(); // Returns unattached empty list
  SVGICCColor            createSVGICCColor();   // Returns empty unattached list
  SVGColor               createSVGColor();      // Returns RGBColor=black, no ICC color
  SVGPaint               createSVGPaint();      // Returns paint of 'none'

  // Generic event creation ability.
  Event                  createEvent(in DOMString type)
                                        raises(DOMException);

  Element                getElementById(in DOMString elementID);
}; 

Methods
suspendRedraw
Takes a time-out value which indicates that redraw shall not occur until: (a) the corresponding unsuspendRedraw(suspend_handle_id) call has been made, (b) an unsuspendRedrawAll() call has been made, or (c) its timer has timed out. In environments that do not support interactivity (e.g., print media), then redraw shall not be suspended. suspend_handle_id = suspendRedraw(max_wait_milliseconds) and unsuspendRedraw(suspend_handle_id) must be packaged as balanced pairs. When you want to suspend redraw actions as a collection of SVG DOM changes occur, then precede the changes to the SVG DOM with a method call similar to suspend_handle_id = suspendRedraw(max_wait_milliseconds) and follow the changes with a method call similar to unsuspendRedraw(suspend_handle_id). Note that multiple suspendRedraw calls can be used at once and that each such method call is treated independently of the other suspendRedraw method calls.
Parameters
max_wait_milliseconds

The amount of time in milliseconds to hold off before redrawing the device. Values greater than 60 seconds will be truncated down to 60 seconds.

Return Value
A number which acts as a unique identifier for the given suspendRedraw() call. This value must be passed as the parameter to the corresponding unsuspendRedraw() method call.

This method raises no exceptions.
unsuspendRedraw
Cancels a specified suspendRedraw() by providing a unique suspend_handle_id.
Parameters
suspend_handle_id

A number which acts as a unique identifier for the desired suspendRedraw() call. The number supplied must be a value returned from a previous call to suspendRedraw().

Return Value
None.
This method will raise a DOMException with value NOT_FOUND_ERR if an invalid value (i.e., no such suspend_handle_id is active) for suspend_handle_id is provided.
unsuspendRedrawAll
Cancels all currently active suspendRedraw() method calls. This method is most useful at the very end of a set of SVG DOM calls to ensure that all pending suspendRedraw() method calls have been cancelled.
Parameters
None.
Return Value
None.
This method raises no exceptions.

6.9.9 Interface SVGGElement

The SVGGElement interface corresponds to the 'g' element.


IDL Definition
interface SVGGElement : SVGStyledAndTransformedElement {
};


6.9.10 Interface SVGDefsElement

The SVGDefsElement interface corresponds to the 'defs' element.


IDL Definition
interface SVGDefsElement : SVGStyledElement {
};


6.9.11 Interface SVGDescElement

The SVGDescElement interface corresponds to the 'desc' element.


IDL Definition
interface SVGDescElement : SVGStyledElement {
};


6.9.12 Interface SVGTitleElement

The SVGTitleElement interface corresponds to the 'title' element.


IDL Definition
interface SVGTitleElement : SVGStyledElement {
};


6.9.13 Interface SVGUseElement

The SVGUseElement interface corresponds to the 'use' element.


IDL Definition
interface SVGUseElement : SVGStyledAndTransformedElement {
  attribute DOMString role;
  attribute DOMString title;
  attribute DOMString show;
  attribute DOMString actuate;
  attribute DOMString href;
  attribute SVGRect viewBox;
  attribute SVGPreserveAspectRatio preserveAspectRatio;

  // XML attributes on the 'use' element.
  attribute SVGLength x;
  attribute SVGLength y;
  attribute SVGLength width;
  attribute SVGLength height;
};


6.9.14 Interface SVGImageElement

The SVGImageElement interface corresponds to the 'image' element.


IDL Definition
interface SVGImageElement : SVGStyledAndTransformedElement {
  attribute DOMString role;
  attribute DOMString title;
  attribute DOMString show;
  attribute DOMString actuate;
  attribute DOMString href;

  attribute SVGRect viewBox;
  attribute SVGPreserveAspectRatio preserveAspectRatio;

  // XML attributes on the 'use' element.
  attribute SVGLength x;
  attribute SVGLength y;
  attribute SVGLength width;
  attribute SVGLength height;
};


6.9.15 Interface SVGSymbolElement

The SVGSymbolElement interface corresponds to the 'symbol' element.


IDL Definition
interface SVGSymbolElement : SVGStyledElement {
  attribute SVGRect viewBox;
  attribute SVGPreserveAspectRatio preserveAspectRatio;

  // XML attributes on the 'svg' element.
  attribute SVGLength refX;
  attribute SVGLength refY;
};