0

I have the following XML string, I want to convert this string to org.w3c.dom.Document in order to get the value of 'CallPaySecureResult' element.

<?xml version="1.0" encoding="UTF-8"?>
<S:Body xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
   <ns2:CallPaySecureResponse xmlns:ns2="https://paysecure/merchant.soap/">
      <CallPaySecureResult>&amp;lt;status&amp;gt;success&amp;lt;/status&amp;gt;&amp;lt;errorcode&amp;gt;0&amp;lt;/errorcode&amp;gt;&amp;lt;errormsg /&amp;gt;&amp;lt;guid&amp;gt;d785f819-6fc1-1c68-8edf-bbb65cba5412&amp;lt;/guid&amp;gt;&amp;lt;/paysecure&amp;gt;</CallPaySecureResult>
   </ns2:CallPaySecureResponse>
</S:Body>

I have tried the following code

public String processIssuerResultParameters(String strXML)throws Exception
    {

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
            DocumentBuilder builder; 
            Document doc=null;
            String CallPaySecureResult ="";
            try  
            {  
                builder = factory.newDocumentBuilder();  
                doc = builder.parse( new InputSource( new StringReader( strXML ) ) ); 
             logger.severe(doc.getTextContent());
            } catch (Exception e) {  
                return "1:"+e.toString()+doc.getTextContent();  
            } 
   }

I have tried this:

InputSource is= new InputSource(new StringReader(strXML));
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            builder = null;
            builder = factory.newDocumentBuilder();
            doc = builder.parse(is);

and this :

Source source = new StreamSource(new StringReader(strXML));
            DOMResult result = new DOMResult();
            TransformerFactory.newInstance().newTransformer().transform(source , result);
            doc = (Document) result.getNode();

But in all the cases variable 'doc' is null.

How can I parse the XML(string) to Document and get the value in <CallPaySecureResult>?

1
  • Use stack snippets if you have code that can run in the browser and 4 spaces or {} button if you have just code. Commented Mar 9, 2016 at 10:50

3 Answers 3

2

Here are some examples + context.

You should take a look at the entire file: https://github.com/bcdev/ceres/blob/master/ceres-metadata/src/main/java/com/bc/ceres/metadata/XPathHandler.java#L76

private static Document transformToDocument(Object document) {
    try {
        String docString;
        if (document instanceof ReaderResource) {
            docString = ((ReaderResource) document).getContent();
        } else if (document instanceof String) {
            docString = (String) document;
        } else if (document instanceof Element) { //used?
            DOMSource domSource = new DOMSource((Element) document);
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            Properties properties = new Properties();
            properties.setProperty(OutputKeys.METHOD, "xml");
            properties.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.setOutputProperties(properties);
            transformer.transform(domSource, result);
            docString = writer.toString();
        } else {
            return null;
        }

        InputStream is = new ByteArrayInputStream(docString.getBytes());
        return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I am not able to convert string to Document. I have tried many ways to convert in to Document.
0

This might help you:

public class Convert {
  public static void main(String[] args) {
    Document copyBookXml = XmlUtils.fileToDom(args[1]);
    Document sourceDocument = XmlUtils.fileToDom(args[0]);
    // params 1) XML source document 2) Copybook as XML
    String result = new XmlToMainframe().convert(sourceDocument, copyBookXml);
    FileUtils.writeFile(result, "mfresult.txt", false);
  }
}

Full code here (code.openhub.net):

http://code.openhub.net/file?fid=e0O83oBJw47fhoPbZm0MgKWWStk&cid=7VtqxYTpWXE&s=Convert%20XML%20string%20to%20org.w3c.dom.Document%3F&pp=0&fl=Java&ff=1&projSelected=false&filterChecked,=true&mp,=1&filterChecked=true&mp=1&ml=1&me=1&md=1#L14

Comments

0

You need to use the namespace when try to get the element, below is the working code:

private static String input = 
     "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
     +"<S:Body xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">"
     +"<ns2:CallPaySecureResponse xmlns:ns2=\"https://paysecure/merchant.soap/\">"
     +"<CallPaySecureResult>&amp;lt;status&amp;gt;success&amp;lt;/status&amp;gt;&amp;lt;errorcode&amp;gt;0&amp;lt;/errorcode&amp;gt;&amp;lt;errormsg /&amp;gt;&amp;lt;guid&amp;gt;d785f819-6fc1-1c68-8edf-bbb65cba5412&amp;lt;/guid&amp;gt;&amp;lt;/paysecure&amp;gt;</CallPaySecureResult>"
     +"</ns2:CallPaySecureResponse>"
     +"</S:Body>";

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
docFactory.setNamespaceAware(true);
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

InputSource is= new InputSource(new StringReader(input));
Document doc = docBuilder.parse(is);

String docNS = "https://paysecure/merchant.soap/";

NodeList nl = doc.getElementsByTagNameNS(docNS, "CallPaySecureResponse");
String s = nl.getLength()> 0 ?nl.item(0).getTextContent():"ELEMENT NOT FOUND";
System.out.println(s);

output:

 &lt;status&gt;success&lt;/status&gt;&lt;errorcode&gt;0&lt;/errorcode&gt;&lt;errormsg /&gt;&lt;guid&gt;d785f819-6fc1-1c68-8edf-bbb65cba5412&lt;/guid&gt;&lt;/paysecure&gt;

hope this can help.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.