如何将XML转换为String并将其传递给Web服务中的java代码?

时间:2013-12-20 06:57:18

标签: java xml web-services soap

嗨,我已经尝试了一段时间..我想在Java Class中解析XML。但是要解析XML,我需要将它传递给java类。我怎么做? 这是在LISA中测试的代码段。

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
    <addnumber xmlns="http://ejb3.examples.itko.com/">
        <firstnumber xmlns="">3</firstnumber>
        <secondnumber xmlns="">22</secondnumber>
    </addnumber>
</soapenv:Body>
</soapenv:Envelope>

它当前在本地主机上运行,​​从那里将值传递给java jar,并且获得的结果将被取消。相同的匹配是

import Calc.Addition; //this the java package to import for addition
String operationname = null;
String operationname = incomingRequest.getOperation(); //incoming request refers to the above xml
String i = incomingRequest.getArguments().get("firstnumber");
String j = incomingRequest.getArguments().get("secondnumber");
int ifirstNumber = Integer.parseInt (i);
int jsecondNumber = Integer.parseInt (j);

Addition myobj = new Addition(ifirstNumber,jsecondNumber ); //values are passed to the constructor of class

int Result = myobj.giveResult(); //function giveResult gives back the sum
String sResponseXML = "";

sResponseXML =       
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" >\n"+
"<soap:Body> \n"+
"<p xsi:type=\"p:ServiceMessageObject\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-  instance\" xmlns:api=\"http://api.webservices.cc.guidewire.com/\" xmlns:util=\"http://UtilLibrary\" xmlns:xa=\"http://XactimateMediationLibrary\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n"+
"<AdditionResult>"+ Result +"</AdditionResult>\n"+
"</p>\n"+
"</soap:Body>\n"+
"</soap:Envelope>";
// Assigning value to the property RESPONSE_XML  
testExec.setStateValue("RESPONSE_XML",sResponseXML );

这是成功执行的正确代码。但是现在我想以字符串的形式将整个上面的XML文件传递给JAVA jar。请帮忙。

1 个答案:

答案 0 :(得分:0)

import java.io.*;
public class Check
{
    public static void main(String [] args)
    {
        BufferedReader br = null;
        try {
            br= new BufferedReader(new FileReader(Fname));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String xmlinput;

        StringBuffer sb= new StringBuffer();
        try {
            while((xmlinput=br.readLine()) !=null)
            {
                sb.append(xmlinput.trim());
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println(sb.toString());
    }
}

现在您将xml的内容作为字符串。