作为 XML 的一个方言，SVG 需要在一个命名空间内（is namespaced）。理解命名空间的概念，以及在你打算编辑SVG内容时，命名空间如何使用，是很重要的。SVG查看器的版本早于Firefox 1.5的发布的，都几乎没有注意命名空间的问题。Versions of SVG viewers prior to the release of Firefox 1.5 unfortunately paid scant attention to namespaces, but they are essential to multi-XML dialect supporting user agents such as Gecko-based browsers which must be very strict. Take some time to understand namespaces now and it will save you all sorts of headaches in future.
W3C的长期目标是使不同类型的XML基本内容可以混合在同一个XML文件中。例如, SVG 和 MathML 可以直接并入基于XHTML的科学文档中。 能够混合这样的内容类型有很多优点，但也需要解决一个非常实际的问题。
合理来说, 每个XML语言定义其规范中描述的标记标签名称的含义。 在单个XML文档中混合来自不同XML方言的内容的问题是，由一个方言定义的标签可能与另一个方言定义的标签具有相同的名称。例如，XHTML和SVG都有一个<title>标签。专业使用者如何区分两者？其实当XML内容是它所知道的，而不仅仅是一个没有意义的包含任意标签名的XML文件时，专业使用者如何告诉它？
与大众想法相反, 这个问题的答案不是“可以从DOCTYPE声明中得知”。DTDs的设计不考虑混合内容，而过去尝试创建混合内容的DTDs现在被认为是失败的。XML和一些XML方言 (包括SVG), 不要求
DOCTYPE 声明，SVG 1.2 更不会有。DOCTYPE声明（通常）与单个内容类型文件中的内容匹配的事实只是巧合的。DTDs仅用于验证，而不是内容的识别。使用其DOCTYPE声明欺骗和标识XML内容的使用者会造成危害（User agents that cheat and identify XML content using its DOCTYPE declaration cause harm）。
So what do these namespace declarations look like, and where do they go? Here is a short example.
<svg xmlns="http://www.w3.org/2000/svg"> <!-- more tags here --> </svg>
The namespace declaration is provided by the
xmlns attribute. This attribute says that the
<svg> tag and its child tags belong to whichever XML dialect has the namespace name 'http://www.w3.org/2000/svg' which is, of course, SVG. Note the namespace declaration only needs to be provided once on a root tag. The declaration defines the default namespace, so the user agent knows that all the
<svg> tag's descendant tags also belong to the same namespace. User agents check to see if they recognize the namespace name to determine if they know how to handle the markup.
Note that namespace names are just strings, so the fact that the SVG namespace name also looks like a URI isn't important. URIs are commonly used because they are unique, the intention is not to "link" somewhere. (In fact URIs are used so frequently that the term "namespace URI" is commonly used instead of "namespace name".)
Redeclaring the default namespace
So if all the descendants of the root tag are also defined to be in the default namespace, how do you mix in content from another namespace? Easy. You just redefine the default namespace. Here's a short example.
<html xmlns="http://www.w3.org/1999/xhtml"> <body> <!-- some XHTML tags here --> <svg xmlns="http://www.w3.org/2000/svg" width="300px" height="200px"> <!-- some SVG tags here --> </svg> <!-- some XHTML tags here --> </body> </html>
In this example the
xmlns attribute on the root
<html> tag declares the default namespace to be XHTML. As a result it and all its child tags are interpreted by the user agent as belonging to XHTML, except for the
<svg> tag. The
<svg> tag has its own
xmlns attribute, and by redeclaring the default namespace, this tells the user agent that the
<svg> tag and its descendants (unless they also redeclare the default namespace) belong to SVG.
See, namespaces really aren't that hard.
Declaring namespace prefixes
XML dialects not only define their own tags, but also their own attributes. By default, attributes don't have a namespace at all, and are only known to be unique because they appear on an element that itself has a unique name. However, sometimes it is necessary to define attributes so that they can be reused on many different elements and still be considered to be the same attribute, independently of the element with which they are used. A very good example of this is the
href attribute defined by the XLink specification. This attribute is commonly used by other XML dialects as a means to link to external resources. But how do you tell the user agent which dialect the attribute belongs to, in this case XLink? Consider the following example.
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <script xlink:href="cool-script.js" type="text/ecmascript"/> </svg>
This example has the rather unusual looking attribute
xmlns:xlink. As you may guess from the first 'xmlns' part, this is another namespace declaration. However, instead of setting the default namespace, this namespace declaration sets the namespace for something called a "namespace prefix". In this case, we have chosen to use the prefix
xlink (the second part) since the prefix will be used to tell the user agent about attributes that belong to XLink.
As their name suggests, namespace prefixes are used to prefix attribute names and tag names. This is done by putting the namespace prefix and a colon before the attribute name as shown on the
<script> tag in the example above. This tells the user agent that that particular attribute belongs to the namespace assigned to the namespace prefix (XLink), and is an attribute that can be used with the same meaning on other tags.
Note that it is an XML error to use a prefix that hasn't been bound to a namespace name. The binding created by the
xmlns:xlink attribute in the example above is absolutely essential if the
xlink:href attribute isn't to cause an error. This XLink attribute is also frequently used in SVG on the
<image> tags among others, so it's a good idea to always include the XLink declaration in your documents.
As an aside, it's useful to know that namespace prefixes can also be used for tag names. This tells the user agent that that particular tag (but not its children this time!) belongs to the namespace assigned to the prefix. Knowing this will save you some confusion if you come across markup like that in the following example:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg"> <body> <h1>SVG embedded inline in XHTML</h1> <svg:svg width="300px" height="200px"> <svg:circle cx="150" cy="100" r="50" fill="#ff0000"/> </svg:svg> </body> </html>
Note that because a namespace prefix is used for the
<svg:svg> tag and its child
<svg:circle>, it wasn't necessary to redeclare the default namespace. In general though it is better to redeclare the default namespace rather than prefix lots of tags in this way.
Scripting in namespaced XML
Namespaces affect not only markup, but also scripting. If you write scripts for namespaced XML such as SVG, read on.
The DOM Level 1 recommendation was created before the original Namespaces in XML recommendation was released; therefore, DOM1 isn't namespace aware. This causes problems for namespaced XML such as SVG. To resolve these problems, DOM Level 2 Core added namespace aware equivalents of all the applicable DOM Level 1 methods. When scripting SVG, it is important to use the namespace aware methods. The table below lists the DOM1 methods that shouldn't be used in SVG, along with their equivalent DOM2 counterparts that should be used instead.
The first argument for all the DOM2 namespace aware methods must be the namespace name (also known as the namespace URI) of the element or attribute in question. For SVG elements this is 'http://www.w3.org/2000/svg'. However, note carefully: the Namespaces in XML 1.1 recommendation states that the namespace name for attributes without a prefix does not have a value. In other words, although the attributes belong to the namespace of the tag, you do not use the tag's namespace name. Instead, you must use null as the namespace name for unqualified (prefixless) attributes. So, to create an SVG
rect element using
document.createElementNS(), you must write:
But to retrieve the value of the
x attribute on an SVG
rect element, you must write:
Note that this isn't the case for attributes with a namespace prefix (attributes that don't belong to the same XML dialect as the tag). Attributes such as the
xlink:href attribute require the namespace name that was assigned to that prefix (http://www.w3.org/1999/xlink for XLink). Hence to get the value of the
xlink:href attribute of an
<a> element in SVG you would write:
For setting attributes that have a namespace, it is recommended (but not required) that you also include their prefix in the second argument so that the DOM can later be more easily converted back to XML (if for instance you want to send it back to the server). For example:
elt.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 'otherdoc.svg');
As a final example, here's a demonstration of how you should dynamically create an
<image> element using script:
var SVG_NS = 'http://www.w3.org/2000/svg'; var XLink_NS = 'http://www.w3.org/1999/xlink'; var image = document.createElementNS(SVG_NS, 'image'); image.setAttributeNS(null, 'width', '100'); image.setAttributeNS(null, 'height', '100'); image.setAttributeNS(XLink_NS, 'xlink:href', 'flower.png');
Make sure you always declare the namespaces you use in your XML files. If you don't, user agents such as Firefox won't recognize your content and will simply show the XML markup or inform the user that there's an error in the XML. It's a good idea to use a template that includes all the commonly used namespace declarations when creating new SVG files. If you don't already have one, make one up starting with the following code:
<svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:ev="http://www.w3.org/2001/xml-events"> </svg>
Even if you don't use all those namespaces in a particular document, there's no harm in including the namespace declarations. It may save you from some annoying errors if you end up adding content from one of the unused namespaces at a later date.
A full example
For a full example see SVG: Namespaces Crash Course: Example.