[jdom-interest] Two namespace-questions

Laurent Bihanic laurent.bihanic at atosorigin.com
Wed May 9 04:11:40 PDT 2007


Kai Wörner a écrit :
> I'm trying to transform a XML-File that lies in a Namespace
> ("http://www.tei-c.org/ns/1.0") to SVG. Since the things I want are a
> pain to implement in XSLT, I switched to Java/JDOM, but now I'm in
> namespace hell:
> The first question: In XSLT (2.0), I can deal with the TEI-namespace
> by declaring
> xpath-default-namespace="http://www.tei-c.org/ns/1.0" - then my
> xpath-expressions work fine without the need to append any prefixes.
> Is there anything like that I can do with JDOM? Every xpath-expression
> I try delivers zero results, regardless of whether I use prefixes or
> not.

There is no default namespace in XPath 1.0.
So you have to use a namespace prefix in your XPath expressions. You can
choose any prefix as there is no relationship between the prefixes used in
XPath and the ones in the document: prefixes are just shortcuts and the
matching is done on the actual namespace URIs.

The following should work:
XPath xp = XPath.newInstance("/x:*");
xp.addNamespace("x", "http://www.tei-c.org/ns/1.0");

> The second question: The resulting SVG-File needs to have a root
> element that defines namespaces like this
> <svg xmlns:svg="http://www.w3.org/2000/svg" 
> xmlns="http://www.w3.org/2000/svg">
> or it won't render in a browser or open in inkscape. I can get the
> first declaration in JDOM via
> Namespace svg = Namespace.getNamespace("svg","http://www.w3.org/2000/svg");
> svgRoot.addNamespaceDeclaration(svg);
> and the second one via
> Namespace svg2 = Namespace.getNamespace("http://www.w3.org/2000/svg");
> svgRoot.setNamespace(svg2);
> , but using the second one adds a
> xmlns=""
> to every Element I create. Is there any comprehensible way to declare
> the namespaces without getting this?

You have to set the namespace on every element you create, for example using 
the constructor Element(java.lang.String name, Namespace namespace) or 
setNamespace(Namespace namespace).
JDOM Elements are not linked to their parent and have a namespace of their 
own. Hence, they do not inherit the parent namespace when being added as children.


More information about the jdom-interest mailing list