前回作成した AbstractCompositeNamespaceContext クラスを用いて、ベースとなる NamespaceContext を持ち、Map のように新に名前空間宣言を登録することも出来る MapNamespaceContext クラスを作成しましょう(一覧)。
基本方針は、以前の記事で作成した MapNamespaceContext と同じです:
import java.util.*; import java.util.Map.Entry; import javax.xml.namespace.NamespaceContext; /** @author waman */ public class MapNamespaceContext extends AbstractCompositeNamespaceContext { private final NamespaceContext parentContext; private final Map<String, String> context; public MapNamespaceContext(){ this(null); } public MapNamespaceContext(NamespaceContext baseContext){ if(baseContext == null) this.parentContext = EmptyContext.INSTANCE; else this.parentContext = baseContext; this.context = new HashMap<String, String>(); } public void put(String prefix, String uri){ this.context.put(prefix, uri); } public void putAll(Map<String, String> map){ this.context.putAll(map); } @Override protected NamespaceContext getParentContext() { return this.parentContext; } @Override protected String getNamespaceURILocally(String prefix) { if(this.context.containsKey(prefix)) return this.context.get(prefix); else return null; } @Override protected Set<String> getPrefixesLocally(String uri) { Set<String> set = new HashSet<String>(); for(Entry<String, String> entry: this.context.entrySet()){ if(entry.getValue().equals(uri)) set.add(entry.getKey()); } return set; } }
使い方は次のような感じ:
MapNamespaceContext context = new MapNamespaceContext(); context.put("xsd", XMLConstants.W3C_XML_SCHEMA_NS_URI ); context.put("rng", XMLConstants. RELAXNG_NS_URI ); System.out.println(context.getNamespaceURI("rng")); // 「http://relaxng.org/ns/structure/1.0」と表示される。