繁体   English   中英

在JAVA中解析XML命名空间(服务器响应)

[英]Parse XML Namespaces (server response), in JAVA

我想显示服务器发送给我的响应,但是在解析时显示给我空字符串。 我已经尝试解析服务器响应,如其他教程中所示,但是它不起作用。 有人知道我做错了吗?

JAVA代码

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class ClienteSoap {
    public static void main(String[] args) {
        HttpClient httpClient = null;   

          try {
            Configuration cfg = new Configuration();

            // Cargar plantilla
            Template template = cfg.getTemplate("src/main/resources/templates/template.ftl");

            // Modelo de datos
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("token", "u757Ric6542ytu6Ricgtr0");
            data.put("branch", "1");
            data.put("app", "S-04600");
            data.put("folio", "4345Ric67");
            data.put("temp", "False");


            // Crear mensaje SOAP HTTP
            StringWriter out = new StringWriter();
            template.process(data, out);
            String strRequest = out.getBuffer().toString();
            System.out.println(strRequest);

            // Crear la llamada al servidor
            httpClient = new DefaultHttpClient();
            HttpPost postRequest = new
            HttpPost("http://127.0.0.1:30005/PCIServicioConciliadorCore-web"); //direccion de la pagina
            StringEntity input = new StringEntity(strRequest);
            input.setContentType("text/xml");
            postRequest.setEntity(input);

            // Tratar respuesta del servidor
            HttpResponse response = httpClient.execute(postRequest);
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new RuntimeException("Error : Código de error HTTP : " + response.getStatusLine().getStatusCode());
            }

            //Obtener información de la respuesta
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            System.out.println(factory);
            Document XMLDoc = factory.newDocumentBuilder().parse(response.getEntity().getContent());
            XPath xpath = XPathFactory.newInstance().newXPath();
            XPathExpression expr = xpath.compile("/AddToken2DBResponseType/Token");
            String result = String.class.cast(expr.evaluate(XMLDoc, XPathConstants.STRING));
            System.out.println("\nEl resultado es: " + result.length());
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            // Cierre de la conexión
            if (httpClient != null) httpClient.getConnectionManager().shutdown();
        }
    }
}

WSDL响应

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
   <SOAP-ENV:Header/>
   <SOAP-ENV:Body>
      <ns2:AddToken2DBResponse xmlns:ns2="http://www.example.com/edit/example">
         <ns2:Token>u757Ric6542ytu6Ricgtr0</ns2:Token>
         <ns2:HandlerError>
            <ns2:statusCode>true</ns2:statusCode>
            <ns2:errorList>
               <ns2:error>
                  <ns2:code>OK</ns2:code>
                  <ns2:origin>JBOSS</ns2:origin>
                  <ns2:userMessage>Primer registro insertado</ns2:userMessage>
                  <ns2:developerMessage>Primer registro insertado</ns2:developerMessage>
               </ns2:error>
            </ns2:errorList>
         </ns2:HandlerError>
      </ns2:AddToken2DBResponse>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

我感谢您的帮助

您的XPath表达式是错误的,如果它以单个/开头,则表示该元素应为/根元素(显然,由于根元素为SOAP-ENV:Envelope它不会找到任何内容)。 到目前为止,它应该是//AddToken2DBResponseType/Token

第二个问题是名称空间。 您有两种选择(我知道):

  • 解析它的名称空间感知并重写xpath以容忍对名称空间的需求。
  • 在不了解的情况下解析名称空间,并在xpath中使用名称空间前缀。

第二个选项非常不稳定,因此这里是第一个:

 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
 factory.setNamespaceAware(true);
 // ...
 XPathExpression expr = xpath.compile("//*[local-name='AddToken2DBResponseType']/*[local-name='Token']");

//*[local-name='abc']任何具有abc(实际上是您想要/需要的名称)的本地名称(没有名称空间的名称)的元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM