Java reading xml element without prefix but within the scope of a namespace
- by wsxedc
Functionally, the two blocks should be the same
<soapenv:Body>
  <ns1:login xmlns:ns1="urn:soap.sof.com">
    <userInfo>
      <username>superuser</username>
      <password>qapass</password>
    </userInfo>
  </ns1:login>
</soapenv:Body>
-----------------------
<soapenv:Body>
  <ns1:login xmlns:ns1="urn:soap.sof.com">
    <ns1:userInfo>
      <ns1:username>superuser</ns1:username>
      <ns1:password>qapass</ns1:password>
    </ns1:userInfo>
  </ns1:login>
</soapenv:Body>
However, how when I read using AXIS2 and I have tested it with java6 as well, I am having a problem.  
 MessageFactory factory = MessageFactory.newInstance();
 SOAPMessage soapMsg = factory.createMessage(new MimeHeaders(), SimpleTest.class.getResourceAsStream("LoginSoap.xml"));
 SOAPBody body = soapMsg.getSOAPBody();
 NodeList nodeList = body.getElementsByTagNameNS("urn:soap.sof.com", "login");
 System.out.println("Try to get login element" + nodeList.getLength());  // I can get the login element
 Node item = nodeList.item(0);
 NodeList elementsByTagNameNS = ((Element)item).getElementsByTagNameNS("urn:soap.sof.com", "username");
 System.out.println("try to get username element " + elementsByTagNameNS.getLength());
So if I replace the 2nd getElementsByTagNameNS with ((Element)item).getElementsByTagName("username");, I am able to get the username element. Doesn't username have ns1 namespace even though it doesn't have the prefix? Am I suppose to keep track of the namespace scope to read an element? Wouldn't it became nasty if my xml elements are many level deep?  Is there a workaround where I can read the element in ns1 namespace without knowing whether a prefix is defined?