Java 解析WSDL的简单方法

Java 解析WSDL的简单方法,java,parsing,wsdl,Java,Parsing,Wsdl,我试图解析WSDL以获取操作、端点和示例有效负载。用户输入的WSDL。我找不到这样做的教程 我只能找到那些生成我不需要的源代码的。我尝试过使用XBeans,但显然我需要Saxon。没有Saxon,有没有一种简单的轻量级方法可以做到这一点 例如 我的第一次发球 应获取操作:GetLastTradePrice,GetLastTradePrice 端点:StockQuotePort 样本有效载荷: <soapenv:Envelope xmlns:soapenv="http://schemas

我试图解析WSDL以获取操作、端点和示例有效负载。用户输入的WSDL。我找不到这样做的教程

我只能找到那些生成我不需要的源代码的。我尝试过使用XBeans,但显然我需要Saxon。没有Saxon,有没有一种简单的轻量级方法可以做到这一点

例如


我的第一次发球
应获取操作:GetLastTradePrice,GetLastTradePrice

端点:StockQuotePort

样本有效载荷:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:stoc="http://example.com/stockquote.xsd">
   <soapenv:Header/>
   <soapenv:Body>
      <stoc:TradePriceRequest/>
   </soapenv:Body>
</soapenv:Envelope>

这就像SoapUI所做的一样。但我主要关心的是能够解析WSDL。更重要的是,WSDL被上传,然后结果显示在GWT应用程序中(文件上传必须转到servlet)。因此,我需要解析文件并创建GWT能够理解的对象。

这看起来不错:

不过,我的第一次尝试并没有成功,所以我编写了一个方法,返回示例wsdl的建议结果—J2SE6之外没有依赖项

public String[] listOperations(String filename) throws FileNotFoundException, SAXException, IOException, ParserConfigurationException {
  Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new FileInputStream(filename));
  NodeList elements = d.getElementsByTagName("operation");
  ArrayList<String> operations = new ArrayList<String>();
  for (int i = 0; i < elements.getLength(); i++) {
    operations.add(elements.item(i).getAttributes().getNamedItem("name").getNodeValue());
  }
  return operations.toArray(new String[operations.size()]);
}
public String[]listOperations(字符串文件名)抛出FileNotFoundException、SAXException、IOException、ParserConfiguration异常{
文档d=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(新文件输入流(文件名));
NodeList elements=d.getElementsByTagName(“操作”);
ArrayList操作=新建ArrayList();
对于(int i=0;i

似乎您希望删除重复项,因为每个操作在WSDL中列出两次。那很容易用一套。上传了完整的eclipse项目,在这里显示了唯一和非唯一的结果:

Hi@Rebzie-can-you-use-JDOM非常简单和轻量级。我使用解析XML文件。我希望能帮助你

私有静态字符串getMethodNameFromWSDL(字符串wsdlPath)抛出FileNotFoundException、SAXException、IOException、ParserConfiguration异常{
字符串tagPrefix=null;
字符串名称空间=null;
字符串位置=空;
NodeList nd=null;
Set operations=newhashset();
NodeList nodeListOfOperations=null;
字符串attr=”http://www.w3.org/2001/XMLSchema"
Document Document=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(新的ByteArrayInputStream(converturturltostring(wsdlPath.getBytes()));
NodeList allnodesofdocument=document.getChildNodes();
对于(int index=0;index0)| |(document.getElementsByTagName(str2.getLength()>0)){
if(document.getElementsByTagName(tagPrefix+“:import”).getLength()>0
nd=document.getElementsByTagName(标记前缀+“:导入”);
else if(document.getElementsByTagName(“wsdl:import”).getLength()>0)
nd=document.getElementsByTagName(“wsdl:import”);
对于(int k=0;k0)| |(document.getElementsByTagName(str4.getLength()>0)){
if(document.getElementsByTagName(str3.getLength()>0){
nodeListOfOperations=document.getElementsByTagName(str3);
}
else if(document.getElementsByTagName(str4.getLength()>0){
nodeListOfOperations=document.getElementsByTagName(str4);
}
对于(int i=0;i

Maven:
org.ow2.easywsdl
easywsdl
2.1
//阅读WSDL 1.1或2.0
WSDLReader reader=WSDLFactory.newInstance().newWSDLReader();
Description desc=reader.read(新URL(“http://file/path/document.wsdl"));
//端点发生在服务中。
//选择一项服务
服务=desc.getServices()。
public String[] listOperations(String filename) throws FileNotFoundException, SAXException, IOException, ParserConfigurationException {
  Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new FileInputStream(filename));
  NodeList elements = d.getElementsByTagName("operation");
  ArrayList<String> operations = new ArrayList<String>();
  for (int i = 0; i < elements.getLength(); i++) {
    operations.add(elements.item(i).getAttributes().getNamedItem("name").getNodeValue());
  }
  return operations.toArray(new String[operations.size()]);
}
 private static String getMethodNameFromWSDL(String wsdlPath) throws FileNotFoundException, SAXException, IOException, ParserConfigurationException {

        String tagPrefix = null;
        String namespace =null;
        String location = null;
        NodeList nd = null;
        Set<String> operations = new HashSet<String>(); 
        NodeList nodeListOfOperations = null;
        String attr ="http://www.w3.org/2001/XMLSchema"

        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(convertURLToString(wsdlPath).getBytes()));

        NodeList allNodesOfDocumnet = document.getChildNodes();

        for(int index = 0;index<allNodesOfDocumnet.getLength();index++){
            if( document.getFirstChild().getNodeName().equalsIgnoreCase("#comment")){
                    document.removeChild(document.getFirstChild());
            }    
        }

       int l =  document.getFirstChild().getAttributes().getLength();
       for (int i = 0; i < l; i++) {
         String cmpAttribute =  document.getFirstChild().getAttributes().item(i).getNodeValue();
             if(cmpAttribute.equals(attr)){
                 tagPrefix =  document.getFirstChild().getAttributes().item(i).getNodeName().replace("xmlns:", "");
             }
        }

        System.out.println(tagPrefix);
        String str1=tagPrefix+":import";
        String str2="wsdl:import";
        String str3 ="operation"; 
        String str4 ="wsdl:operation"; 
        // Getting Namespace
                if((document.getElementsByTagName(str1).getLength()>0)||(document.getElementsByTagName(str2).getLength()>0)){

                            if(document.getElementsByTagName(tagPrefix+":import").getLength()>0)
                                 nd =document.getElementsByTagName(tagPrefix+":import");

                            else if (document.getElementsByTagName("wsdl:import").getLength()>0) 
                                 nd =document.getElementsByTagName("wsdl:import");  

                            for (int k = 0; k < nd.item(0).getAttributes().getLength(); k++) {
                                String strAttributes = nd.item(0).getAttributes().item(k).getNodeName();

                                if(strAttributes.equalsIgnoreCase("namespace")){
                                    namespace = nd.item(0).getAttributes().item(k).getNodeValue();
                                    System.out.println("Namespace : "+namespace);
                                }
                                else {
                                     location = nd.item(0).getAttributes().item(k).getNodeValue();
                                     System.out.println("Location : "+location);
                                }

                            }
                }else{
                        namespace = document.getFirstChild().getAttributes().getNamedItem("targetNamespace").getNodeValue();
                        System.out.println("Namespace : "+namespace);
                    }   



                //Getting  Operations 

                 if((document.getElementsByTagName(str3).getLength()>0)||(document.getElementsByTagName(str4).getLength()>0)){

                    if(document.getElementsByTagName(str3).getLength()>0){
                        nodeListOfOperations =document.getElementsByTagName(str3);
                    }
                    else if (document.getElementsByTagName(str4).getLength()>0) {
                         nodeListOfOperations =document.getElementsByTagName(str4);
                    }
                    for (int i = 0; i < nodeListOfOperations.getLength(); i++) {
                            operations.add(nodeListOfOperations.item(i).getAttributes().getNamedItem("name").getNodeValue()); 
                    }

                }   

            if(location!=null){ 
                if(operations.isEmpty()){   
                    Document documentForOperation = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(convertURLToString(location).getBytes()));
                    NodeList nodesOfNewDoc = documentForOperation.getChildNodes();
                    for(int index = 0;index<nodesOfNewDoc.getLength();index++){
                        if( documentForOperation.getFirstChild().getNodeName().equalsIgnoreCase("#comment")){
                                document.removeChild(document.getFirstChild());
                        }       
                    }

                    NodeList nodeList  = documentForOperation.getElementsByTagName(str4);
                    for (int i = 0; i < nodeList.getLength(); i++) {
                        operations.add(nodeList.item(i).getAttributes().getNamedItem("name").getNodeValue()); 
                    }
                }

            }

            for (String string : operations) {
                System.out.println(string);
            }
       System.out.println(operations.toString());           
        return operations.toString();           
    }

public static String convertURLToString(String url){

    StringBuilder response = null;  

    try {    

        URL urlObj = new URL(url);
        URLConnection urlConnection = urlObj.openConnection();
        urlConnection.setDoOutput(true);
        urlConnection.connect();    
        //urlConnection.setConnectTimeout(30000);       
        BufferedReader reader = new BufferedReader(new 
           InputStreamReader(urlConnection.getInputStream()));
        response = new StringBuilder();
        String inputLine;

        while ((inputLine = reader.readLine()) != null){
            response.append(inputLine);
        }

        reader.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    return response.toString();     
}
Maven:
<dependency>
  <groupId>org.ow2.easywsdl</groupId>
  <artifactId>easywsdl-wsdl</artifactId>
  <version>2.1</version>
</dependency>


// Read a WSDL 1.1 or 2.0
WSDLReader reader = WSDLFactory.newInstance().newWSDLReader();
Description desc = reader.read(new URL("http://file/path/document.wsdl"));
// Endpoints take place in services. 
// Select a service
Service service = desc.getServices().get(0);

// List endpoints
List<Endpoint> endpoints = service.getEndpoints(); 

// Read specific endpoint
//An endpoint has getBinding and then you getInterface from binding and so on
Endpoint specificEndpoint = service.getEndpoint("endpointName");

// Add endpoint to service
service.addEndpoint(specificEndpoint);

// Remove a specific enpoint
service.removeEndpoint("endpointName");

// Create endpoint
Endpoint createdEndpoint = service.createEndpoint();
service.addEndpoint(createdEndpoint);

My sample code:
    try {
        // Read a WSDL 1.1 or 2.0
        WSDLReader reader = WSDLFactory.newInstance().newWSDLReader();
        Description desc = reader.read(new URL("file:///C:/your/file/path/sample.wsdl"));
        // Endpoints take place in services. 
        // Select a service
        Service service = desc.getServices().get(0);
        List<Endpoint> endpoints = service.getEndpoints();
        //Gets address of first endpoint
        System.out.println(endpoints.get(0).getAddress());
        //Gets http method
        System.out.println(endpoints.get(0).getBinding().getBindingOperations().get(0).getHttpMethod());
        //Gets input type
        System.out.println(endpoints.get(0).getBinding().getInterface().getOperations().get(0).getInput().getElement().getType().getQName().getLocalPart());

    } catch (WSDLException | IOException | URISyntaxException e1) {
        e1.printStackTrace();
    }