001/* 002 * ModeShape (http://www.modeshape.org) 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.modeshape.common.xml; 017 018import java.util.HashMap; 019import java.util.Iterator; 020import java.util.Map; 021import javax.xml.namespace.NamespaceContext; 022 023/** 024 * A simple {@link NamespaceContext} implementation that maintains the namespace and prefix mappings discovered within an XML 025 * document. 026 */ 027public class SimpleNamespaceContext implements NamespaceContext { 028 029 private final Map<String, String> prefixToNamespace = new HashMap<String, String>(); 030 031 @Override 032 public String getNamespaceURI( String prefix ) { 033 return this.prefixToNamespace.get(prefix); 034 } 035 036 @Override 037 public String getPrefix( String namespaceURI ) { 038 for (Map.Entry<String, String> entry : this.prefixToNamespace.entrySet()) { 039 if (entry.getValue().equals(namespaceURI)) return entry.getKey(); 040 } 041 return null; 042 } 043 044 public SimpleNamespaceContext setNamespace( String prefix, 045 String namespaceUri ) { 046 this.prefixToNamespace.put(prefix, namespaceUri); 047 return this; 048 } 049 050 @Override 051 public Iterator<String> getPrefixes( String namespaceURI ) { 052 return this.prefixToNamespace.keySet().iterator(); 053 } 054 055}