Read XML with Java

Asked

Viewed 830 times

1

I’m using the following code to send a .xml via SOAP

package consumirwebserviceporrequisicaoxml;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;

/**
 *
 * @author kite
 */
public class ConsumirWebServicePorRequisicaoXML {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws SOAPException, IOException {
        // TODO code application logic here
        // TODO code application logic here
        String requestSoap;//requisicao/request no formato xml, repare que isto foi copiado da regiao destacada em azul na figura 1
        requestSoap =  "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\">\n"
+ "   <soapenv:Header/>\n"
+ "   <soapenv:Body>\n"
+ "      <tem:CalcPrazo>\n"
+ "         <!--Optional:-->\n"
+ "         <tem:nCdServico>40010</tem:nCdServico>\n"
+ "         <!--Optional:-->\n"
+ "         <tem:sCepOrigem>01207000</tem:sCepOrigem>\n"
+ "         <!--Optional:-->\n"
+ "         <tem:sCepDestino>01504001</tem:sCepDestino>\n"
+ "      </tem:CalcPrazo>\n"
+ "   </soapenv:Body>\n"
+ "</soapenv:Envelope>";
        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection soapConnection = soapConnectionFactory.createConnection();
        String url = "http://ws.correios.com.br/calculador/CalcPrecoPrazo.asmx";//url do webservice nao e a url do wsdl do webservice, repare que isto foi copia da parte vermelha da figura 1
        MimeHeaders headers = new MimeHeaders();
        headers.addHeader("Content-Type", "text/xml");

        //exclua esta regiao caso o webservice nao possua a proprieade SOAPAction
        headers.addHeader("SOAPAction", "http://tempuri.org/CalcPrazo"); // header SOAPAction e sua respectiva url, esta url muda de webservice para webservice. Alguns webservice nao possuem esta proprieade, nestes webservice esta linha deve ser excluida
                                                                         // o valor "http://tempuri.org/CalcPrazo" foi obtido com base na região destacada em verde da figura 2.

        //fim da regiao a ser excluida caso o webservice nao possua a proprieade SOAPAction

        MessageFactory messageFactory = MessageFactory.newInstance();

        SOAPMessage msg = messageFactory.createMessage(headers, (new ByteArrayInputStream(requestSoap.getBytes())));

        SOAPMessage soapResponse = soapConnection.call(msg, url);
        Document xmlRespostaARequisicao=soapResponse.getSOAPBody().getOwnerDocument();
        System.out.println(passarXMLParaString(xmlRespostaARequisicao,4));//imprime na tela o xml de retorno.
    }
    public static String passarXMLParaString(Document xml, int espacosIdentacao){
        try {
            //set up a transformer
            TransformerFactory transfac = TransformerFactory.newInstance();
            transfac.setAttribute("indent-number", new Integer(espacosIdentacao));
            Transformer trans = transfac.newTransformer();
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            trans.setOutputProperty(OutputKeys.INDENT, "yes");

            //create string from xml tree
            StringWriter sw = new StringWriter();
            StreamResult result = new StreamResult(sw);
            DOMSource source = new DOMSource(xml);
            trans.transform(source, result);
            String xmlString = sw.toString();
            return xmlString;
        }
        catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.exit(0);
        }
        return null;
    }
}

However, how do I do for the content of requestSoap come from a file .xml and not of values entered in the variable?

1 answer

2


In Java this is simple. You just need to create a method to read a file:

static String readFile(String path, Charset encoding) throws IOException 
{
  byte[] encoded = Files.readAllBytes(Paths.get(path));
  return new String(encoded, encoding);
}

In this method the parameter is passed path which contains the complete file path, and encoding with coding.

The result is a string with the contents of the file.

An example of use would be:

String requestSoap = readFile("c:\\arq.xml", Charset.defaultCharset());

Browser other questions tagged

You are not signed in. Login or sign up in order to post.