Skip to Content.
Sympa Menu

xom-interest - [XOM-interest] Getting the prefix of a namespace knowing the URI

xom-interest AT lists.ibiblio.org

Subject: XOM API for Processing XML with Java

List archive

Chronological Thread  
  • From: Laurent Bihanic <laurent.bihanic AT atosorigin.com>
  • To: XOM-interest <XOM-interest AT lists.ibiblio.org>
  • Subject: [XOM-interest] Getting the prefix of a namespace knowing the URI
  • Date: Fri, 07 Feb 2003 13:45:55 +0100

Hi,

I need to pre-process an XML document to add some information to it. The elements to be added shall belong to a known namespace, already defined in the document. I want to avoid re-declaring this namespace with a new prefix and thus I need to retrieve the namespace prefix knowing the URI.

I found no way in XOM to do this but found a solution using XPath. Yet, it would be nice for XOM to provide a "native" solution.

I'm proposing to add a new getNamespacePrefix(String uri) method to Element (see below for a possible implementation). I tested it and it works fine once the getNamespaceURI bug I reported earlier fixed.

public String getNamespacePrefix(String uri) {
if ((uri == null) || (uri.length() == 0)) {
throw new IllegalArgumentException("uri");
}

// Check node own namespace first.
if (uri.equals(this.getNamespaceURI())) {
return this.getNamespacePrefix();
}

// Check default namespace in scope.
if (uri.equals(this.getNamespaceURI(null))) {
return "";
}

// Search ancestor-or-self nodes for namespace declaration.
Element current = this;
while (current != null) {
prefix = current.getNamespacePrefix();

if ((prefix != null) && (prefix.length() != 0) &&
(uri.equals(current.getNamespaceURI()))) {
return prefix;
}

int max = current.getNamespaceDeclarationCount();
for (int i=0; i<max; i++) {
prefix = current.getNamespacePrefix(i);

if ((prefix != null) && (prefix.length() != 0) &&
(uri.equals(current.getNamespaceURI(prefix)))) {
return prefix;
}
}
ParentNode parent = current.getParent();
current = (parent instanceof Element)? (Element)parent: null;
}
return null;
}

Laurent





Archive powered by MHonArc 2.6.24.

Top of Page