import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
public class CheckNS {
private static void dump(String xmlstr) throws ParserConfigurationException, SAXException, IOException {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
xr.setContentHandler(new DumpParser());
xr.parse(new InputSource(new StringReader(xmlstr)));
}
public static void main(String[] args) throws Exception {
String xml = "<a:foo qux=\"A\" xmlns:a=\"B\" xmlns:b=\"C\">\r\n" +
" <b:bar a:quux=\"D\" xmlns=\"E\"/>\r\n" +
" <xmlns xmlns:a=\"F\" xmlns=\"G\">\r\n" +
" <baz a:corge=\"H\" xmlns:baz=\"I\" xmlns=\"\"/>\r\n" +
" </xmlns>" +
"</a:foo>\r\n";
System.out.print(xml);
dump(xml);
}
}
class DumpParser extends DefaultHandler {
public void startElement(String namespaceURI, String localName, String rawName, Attributes atts) throws SAXException {
System.out.printf("Element: ns=%s name=%s\n", namespaceURI, localName);
for(int i = 0; i < atts.getLength(); i++) {
System.out.printf(" Attribute: ns=%s name=%s\n", atts.getURI(i), atts.getLocalName(i));
}
}
}