View RSS Feed

My Java Tips

Binding a single namespace

Rate this Entry
by , 11-01-2011 at 07:16 PM (706 Views)
The XPath expression that finds the titles of all of Laiq's books will be //pre:book[pre:author="Laiq"]/pre:title/text(). However, you have to map the prefix pre to the URI.



It's a little strange that the Namespace Context interface doesn't have a default implementation in the Java software development kit (JDK) or JAXP, but it doesn't. However, it's not hard to implement. Following simple implementation is for one namespace. You should map the xml prefix as well.

Java Code:
import java.util.Iterator;
import javax.xml.*;
import javax.xml.namespace.NamespaceContext;

public class PersonalNamespaceContext implements NamespaceContext {

    public String getNamespaceURI(String prefix) {
        if (prefix == null) throw new NullPointerException("Null prefix");
        else if ("pre".equals(prefix)) return "http://www.example.org/books";
        else if ("xml".equals(prefix)) return XMLConstants.XML_NS_URI;
        return XMLConstants.NULL_NS_URI;
    }

    // This method isn't necessary for XPath processing.
    public String getPrefix(String uri) {
        throw new UnsupportedOperationException();
    }

    // This method isn't necessary for XPath processing either.
    public Iterator getPrefixes(String uri) {
        throw new UnsupportedOperationException();
    }

}

Submit "Binding a single namespace" to Facebook Submit "Binding a single namespace" to Digg Submit "Binding a single namespace" to del.icio.us Submit "Binding a single namespace" to StumbleUpon Submit "Binding a single namespace" to Google

Tags: None Add / Edit Tags
Categories
XML

Comments