Action against software patentsGnome2 LogoW3C LogoRed Hat Logo
Made with Libxml2 Logo

The XML C parser and toolkit of Gnome

Namespaces

Main Menu
Related links

The libxml2 library implements XML namespacessupport byrecognizing namespace constructs in the input, and does namespace lookupautomatically when building the DOM tree. A namespace declaration isassociated with an in-memory structure and all elements or attributes withinthat namespace point to it. Hence testing the namespace is a simple and fastequality operation at the user level.

I suggest that people using libxml2 use a namespace, and declare it in theroot element of their document as the default namespace. Then they don't needto use the prefix in the content but we will have a basis for future semanticrefinement and merging of data from different sources. This doesn't increasethe size of the XML output significantly, but significantly increases itsvalue in the long-term. Example:

<mydoc xmlns="http://mydoc.example.org/schemas/">
   <elem1>...</elem1>
   <elem2>...</elem2>
</mydoc>

The namespace value has to be an absolute URL, but the URL doesn't have topoint to any existing resource on the Web. It will bind all the element andattributes with that URL. I suggest to use an URL within a domain youcontrol, and that the URL should contain some kind of version information ifpossible. For example, "http://www.gnome.org/gnumeric/1.0/"is agood namespace scheme.

Then when you load a file, make sure that a namespace carrying theversion-independent prefix is installed on the root element of your document,and if the version information don't match something you know, warn the userand be liberal in what you accept as the input. Also do *not* try to basenamespace checking on the prefix value. <foo:text> may be exactly thesame as <bar:text> in another document. What really matters is the URIassociated with the element or the attribute, not the prefix string (which isjust a shortcut for the full URI). In libxml, element and attributes have annsfield pointing to an xmlNs structure detailing the namespaceprefix and its URI.

@@Interfaces@@

xmlNodePtr node;
if(!strncmp(node->name,"mytag",5)
  && node->ns
  && !strcmp(node->ns->href,"http://www.mysite.com/myns/1.0")) {
  ...
}

Usually people object to using namespaces together with validity checking.I will try to make sure that using namespaces won't break validity checking,so even if you plan to use or currently are using validation I stronglysuggest adding namespaces to your document. A default namespace schemexmlns="http://...."should not break validity even on lessflexible parsers. Using namespaces to mix and differentiate content comingfrom multiple DTDs will certainly break current validation schemes. To checksuch documents one needs to use schema-validation, which is supported inlibxml2 as well. See relagx-ngand w3c-schema.

Daniel Veillard