Working XML

Compiling the paths and automating tests

A closer look at algorithms and JUnit

Return to article.

Listing 1. QName.java
package org.ananas.hc;
import java.text.MessageFormat;
public class QName
{
   public final static int ROOT = 1,
                           ELEMENT = 2,
                           ATTRIBUTE = 3;
   private String namespaceURI,
                  localName;
   private int type;
   public QName(int type,String namespaceURI,String localName)
   {
      if(localName == null)
         throw new IllegalArgumentException("local name cannot be null");
      else
      {
         this.namespaceURI = namespaceURI == null ? "".intern() : namespaceURI.intern();
         this.localName = localName.intern();
      }
      if(type < ROOT || type > ATTRIBUTE)
         throw new IllegalArgumentException("unknown type");
      else
         this.type = type;
   }
   public String getNamespaceURI()
   {
      return namespaceURI;
   }
   public String getLocalName()
   {
      return localName;
   }
   public int getType()
   {
      return type;
   }
   public boolean equals(Object object)
   {
      if(object instanceof QName)
      {
         QName qname = (QName)object;
         return namespaceURI == qname.namespaceURI &&
                localName == qname.localName &&
                type == qname.type;
      }
      else
         return false;
   }
   public int hashCode()
   {
      // don't worry about the type, it's uncommon enough that
      // elements and attributes have the same name that it should
      // not result in too many collisions
      return namespaceURI.hashCode() ^ localName.hashCode();
   }
   public String toString()
   {
      return MessageFormat.format(type == ATTRIBUTE ? "'{'{0}'}'{1}" :
                                                      "'{'{0}'}'@{1}",
                                  new Object[] { namespaceURI,
                                                 localName });
   }
}

Return to article.