解析Xml DocumentBuilder

时间:2018-04-18 16:03:47

标签: java

我尝试使用documentbuilder将xml结果转换为字符串。我构建了以下函数,以便从数据库中获取所有结果,当我将它们存储在列表中并将它们发送到列表时一切都很好,但是当我尝试将结果显示为字符串xml时,下一个错误就会出现起来。

WS00041: Service invocation threw an exception with message : null; Refer to the server log for more details
Exceptions details : java.lang.reflect.InvocationTargetException
javax.servlet.ServletException: java.lang.reflect.InvocationTargetException
    at org.glassfish.webservices.monitoring.WebServiceTesterServlet.doPost(WebServiceTesterServlet.java:342)
    at org.glassfish.webservices.monitoring.WebServiceTesterServlet.invoke(WebServiceTesterServlet.java:106)
    at org.glassfish.webservices.JAXWSServlet.doPost(JAXWSServlet.java:157)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
    at java.lang.Thread.run(Thread.java:748) Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.glassfish.webservices.monitoring.WebServiceTesterServlet.doPost(WebServiceTesterServlet.java:313) ... 32 more
    Caused by: com.sun.xml.ws.fault.ServerSOAPFaultException: Client received SOAP Fault from server: java.lang.IllegalArgumentException: Can not set java.util.List field NewWebServiceMaterias.jaxws.GetMateriaResponse._return to java.lang.String Please see the server log to find more detail regarding exact cause of the failure.
    at com.sun.xml.ws.fault.SOAP11Fault.getProtocolException(SOAP11Fault.java:193)
    at com.sun.xml.ws.fault.SOAPFaultBuilder.createException(SOAPFaultBuilder.java:131)
    at com.sun.xml.ws.client.sei.StubHandler.readResponse(StubHandler.java:253)
    at com.sun.xml.ws.db.DatabindingImpl.deserializeResponse(DatabindingImpl.java:203)
    at com.sun.xml.ws.db.DatabindingImpl.deserializeResponse(DatabindingImpl.java:290)
    at com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:119)
    at com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:92)
    at com.sun.xml.ws.client.sei.SEIStub.invoke(SEIStub.java:161)
    at com.sun.proxy.$Proxy283.getMateria(Unknown Source) ... 37 more

代码:

    @WebMethod(operationName = "getMateria")
    public String getMateria() {
        Conexion c = new Conexion();
        Connection cn = c.Conectar();
        List<Materia> materia;
        String mensaje;
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder;
        try {
            docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("materia");
            doc.appendChild(rootElement);
            try {
                Statement st = cn.createStatement();
                ResultSet rs = st.executeQuery("select * from asignaturas");
                materia = new ArrayList<>();
                while (rs.next()) {
                    materia.add(new Materia(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4)));
                    Element nombreMateria = doc.createElement("nombre");
                    nombreMateria.appendChild(doc.createTextNode(rs.getString(3)));
                    Element detMateria = doc.createElement("detalle");
                    detMateria.appendChild(doc.createTextNode(rs.getString(4)));
                    rootElement.appendChild(nombreMateria);
                    rootElement.appendChild(detMateria);
                }
                TransformerFactory tf = TransformerFactory.newInstance();
                Transformer transformer = tf.newTransformer();
                //transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                StringWriter writer = new StringWriter();
                transformer.transform(new DOMSource(doc), new StreamResult(writer));
                String output = writer.getBuffer().toString().replaceAll("\n|\r", "");
                return output;

            } catch (SQLException | DOMException | TransformerException e) {
                mensaje = "este es un error" + e.getMessage();
            }
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(NewWebServiceMaterias.class.getName()).log(Level.SEVERE, null, ex);
            mensaje = "ESTAMOS EN EL ERROR 1" + ex.getMessage();
        }

        return mensaje + "El valor no se ha encontrado";
    }

1 个答案:

答案 0 :(得分:0)

可能的原因之一:从右到左的顺序检索列值,然后检索一次:

while (rs.next()) {
    materia.add(new Materia(rs.getInt(1), 
        rs.getString(2), rs.getString(3), rs.getString(4)));
    // skipped
    nombreMateria.appendChild(doc.createTextNode(rs.getString(3)));
    detMateria.appendChild(doc.createTextNode(rs.getString(4)));
    // skipped
}

这可能导致您期望(在Materia构造函数中或在您调用apendChild(...)时)与获得的内容之间不匹配(调用getString(...)可以返回NULL )。

documentation中所述:

  

默认ResultSet对象不可更新且具有光标   只向前迈进。因此,您只需迭代一次即可   仅从第一行到最后一行。

     

为了获得最大的可移植性,每行中的结果集列应该是   按从左到右的顺序读取,每列应只读一次。