fork(1) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import javax.xml.namespace.NamespaceContext;
  7. import javax.xml.parsers.*;
  8. import javax.xml.*;
  9. import org.w3c.dom.*;
  10. import javax.xml.xpath.*;
  11. import org.xml.sax.*;
  12.  
  13. /* Name of the class has to be "Main" only if the class is public. */
  14. class Ideone
  15. {
  16. public static void main (String[] args) throws java.lang.Exception
  17. {
  18. // javax.xml.parsers.*
  19. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  20. factory.setNamespaceAware(true);
  21. DocumentBuilder builder = factory.newDocumentBuilder();
  22. String xml = "<soap:Envelope xmlns:soap=\"http://w...content-available-to-author-only...3.org/2003/05/soap-envelope\">" +
  23. "<soap:Header>" +
  24. "<context xmlns=\"urn:zimbra\"><session id=\"555\">555</session><change token=\"333\"/></context>" +
  25. "</soap:Header>" +
  26. "</soap:Envelope>";
  27.  
  28. InputSource is = new InputSource(new StringReader(xml));
  29. Document doc = builder.parse(is);
  30.  
  31. XPathFactory xPathfactory = XPathFactory.newInstance();
  32. XPath xpath = xPathfactory.newXPath();
  33. xpath.setNamespaceContext(new NamespaceContext() {
  34. @Override
  35. public String getNamespaceURI(String prefix) {
  36. if (prefix.equals("soap")) {
  37. return "http://w...content-available-to-author-only...3.org/2003/05/soap-envelope";
  38. }
  39. if (prefix.equals("zmb")) {
  40. return "urn:zimbra";
  41. }
  42.  
  43. return XMLConstants.NULL_NS_URI;
  44. }
  45.  
  46. @Override
  47. public String getPrefix(String namespaceURI) {
  48. throw new UnsupportedOperationException("Not supported yet.");
  49. }
  50.  
  51. @Override
  52. public Iterator getPrefixes(String namespaceURI) {
  53. throw new UnsupportedOperationException("Not supported yet.");
  54. }
  55. });
  56.  
  57. XPathExpression expr =
  58. xpath.compile("/soap:Envelope/soap:Header/zmb:context/zmb:session");
  59. String sessionId = (String)expr.evaluate(doc, XPathConstants.STRING);
  60. System.out.println(sessionId);
  61. }
  62. }
Success #stdin #stdout 0.14s 382144KB
stdin
Standard input is empty
stdout
555