Skip to Main Content

Java EE (Java Enterprise Edition) General Discussion

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Not able to get namespace URI / prefix of XML elements using DOM parser

843834Sep 21 2008 — edited Sep 23 2008
Hi All,

I was working with parsing XML using DOM parser. From a XML file I wanted to get the namespace URI, prefix of the document element. And I also wanted to read the "child" element's values by their namespace and prefix.

Please find the xml file,
<?xml version="1.0" encoding="UTF-8"?>
<pri:parent xmlns:pri="http://www.W3.org/1999/XSL/Transform">
	<pri:child>
		<pri:name>User1</pri:name>
	</pri:child>
	<sec:child xmlns:sec="http://www.w3.org/1999/xsl/Transform">
		<sec:name>User2</sec:name>
	</sec:child>
</pri:parent>
Please refer to the java code that I used,
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = null;
		Document doc = null;
		try {
			builder = factory.newDocumentBuilder();
			doc = builder.parse(new File("input.xml"));
			System.out.println("Doc namespace: " + doc.getNamespaceURI());
			System.out.println("Prefix using lookuPrefix: " + doc.getDocumentElement().lookupPrefix("http://www.W3.org/1999/XSL/Transform"));
			System.out.println("URI using getNamespaceURI: " + doc.getDocumentElement().getNamespaceURI());
			System.out.println("URI: " + doc.getDocumentElement().lookupNamespaceURI("pri"));
			Element ele = doc.getDocumentElement();
			System.out.println(doc.getDocumentElement().getNodeName());
			NodeList list = ele.getElementsByTagName("pri:child");
			NodeList nsList = ele.getElementsByTagNameNS("http://www.w3.org/1999/xsl/Transform", "child");
			NodeList prefixList = ele.getElementsByTagName("sec:child");
			System.out.println("Prefixed Primary childs: " + list.getLength());
			System.out.println("Namespace-d Secondary childs:" + nsList.getLength());
			System.out.println("Prefixed Secondary childs: " + prefixList.getLength());
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
Please find below the output of my java code.
Doc namespace: null
Prefix using lookuPrefix: null
URI using getNamespaceURI: null
URI: null
pri:parent
Prefixed Primary childs: 1
Namespace-d Secondary childs:0
Prefixed Secondary childs: 1
I wasnt able to get the namespace URI / associated prefix or the child element's values by their namespace and prefix. I was getting null for all of the cases that dealt with namespace names.

Please suggest me ways to solve this problem.

Thanks & Regards,
Senthil
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Oct 21 2008
Added on Sep 21 2008
2 comments
855 views