Java reading xml element without prefix but within the scope of a namespace

Posted by wsxedc on Stack Overflow See other posts from Stack Overflow or by wsxedc
Published on 2010-05-13T22:02:26Z Indexed on 2010/05/13 22:04 UTC
Read the original article Hit count: 206

Filed under:
|
|
|

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?

© Stack Overflow or respective owner

Related posts about java

Related posts about soap